﻿unit uFrmMain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, GR32, Controls, Forms,
  Dialogs, ComCtrls, Menus, ImgList, CommCtrl, StdCtrls, Grids, WideStrings,
  DBXOracle, DB, SqlExpr, FMTBcd, Oracle, OracleMonitor, jpeg, ExtCtrls, StrUtils,
  uFrmSelectObjects, uFrmSellTicket, ufrmCageTournament, uUtils, OracleData,
  ExtDlgs, uFrmChangePassword, Buttons, pngimage, dblookup,
  DBCtrls, ActnList, uFrmCameraGetImage, uFraPlayers, gnugettext, inifiles,
  DBGrids, DBTables, uFrmAbout, editusers, edittables, editwindist, uSQLs, EditWinNumPlayers,
  editwinpercentage, editprofiles, edittournaments, edittournamentrounds, editplayernotes, editplayers,
  AppEvnts, editcashgames, editroundtypes, ufrmcagecashgame, ufrmtable, ufrmhall, ufrmloading, editcountries, editdrinks,
  uMainUtils, ufrmtableusegraph, EditTableZones, uFrmEMailing, xmldom, Xmlxform,
  XMLIntf, msxmldom, XMLDoc, EditCasinoInventory, uupdateapp, ufrmprintcageclose, ufrmprintdata, shellapi, ADODB, DBClient, ufrmcageinventory, edittournamenttypes, uprintbarbill, editrakes,
  editrakevalues,printers, Graphics, ufrmorderdrink, GR32_Image, XPMan, ScktComp, uImagePanel, uFrmSubjectImage, uFrmDealerSelect;

type
  TFrmMain = class(TForm)
    MainMenu: TMainMenu;
    ddd1: TMenuItem;
    Close1: TMenuItem;
    StatusBar1: TStatusBar;
    iml_Modules: TImageList;
    OracleSession1: TOracleSession;
    OracleQuery1: TOracleQuery;
    OpenPictureDialog1: TOpenPictureDialog;
    Settings1: TMenuItem;
    ActionList1: TActionList;
    act_Users: TAction;
    act_Tables: TAction;
    act_Players: TAction;
    act_Profiles: TAction;
    act_TournamentReports: TAction;
    act_PrepareTournament: TAction;
    act_WinDistribution: TAction;
    act_BreakTable: TAction;
    act_Tickets: TAction;
    act_Settings: TAction;
    act_UserAccess: TAction;
    act_Login: TAction;
    act_CanChangePassword: TAction;
    ChangePassword1: TMenuItem;
    pnl_Split: TPanel;
    pnl_MainMenu: TPanel;
    pnl_MenuDetail: TPanel;
    btn_Profiles: TSpeedButton;
    btn_WinDistribution: TSpeedButton;
    pnl_MenuMaster: TPanel;
    btn_MenuUsers: TSpeedButton;
    btn_MenuTickets: TSpeedButton;
    btn_MenuReport: TSpeedButton;
    btn_MenuPlayers: TSpeedButton;
    btn_MenuPrepareTournament: TSpeedButton;
    Panel4: TPanel;
    img_Logo: TImage;
    act_Tournaments: TAction;
    btn_UserAccess: TSpeedButton;
    btn_Tables: TSpeedButton;
    About1: TMenuItem;
    BalloonHint: TBalloonHint;
    btn_PlayerPoints: TSpeedButton;
    act_PlayerPoints: TAction;
    btn_ReportDataTracking: TSpeedButton;
    act_DataTracking: TAction;
    Login1: TMenuItem;
    btn_Logout: TButton;
    ApplicationEvents1: TApplicationEvents;
    btn_ReportTournament: TSpeedButton;
    btn_TicketsTournament: TSpeedButton;
    act_TicketsCashGame: TAction;
    act_TicketsTournament: TAction;
    btn_TicketsCashGame: TSpeedButton;
    btn_MenuPrepareCashGame: TSpeedButton;
    act_PrepareCashGame: TAction;
    btn_MenuGeneral: TSpeedButton;
    act_General: TAction;
    pnl_ActiveMenuButton: TPanel;
    pnl_ActiveSubMenuButton: TPanel;
    btn_RoundTypes: TSpeedButton;
    tmr_Alert: TTimer;
    btn_MenuHallView: TSpeedButton;
    pgc_Main: TPageControl;
    tbs_CageTournament: TTabSheet;
    tbs_Users: TTabSheet;
    Panel1: TPanel;
    stg_UserProfiles: TStringGrid;
    Panel31: TPanel;
    SpeedButton34: TSpeedButton;
    Label1: TLabel;
    Panel3: TPanel;
    img_User: TImage;
    Label9: TLabel;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Panel8: TPanel;
    stg_Users: TStringGrid;
    pnl_Users: TPanel;
    btn_New: TSpeedButton;
    btn_Edit: TSpeedButton;
    btn_Duplicate: TSpeedButton;
    btn_Delete: TSpeedButton;
    Label12: TLabel;
    btn_ChangePassword: TButton;
    tbs_Tables: TTabSheet;
    Panel13: TPanel;
    stg_Tables: TStringGrid;
    Panel14: TPanel;
    SpeedButton1: TSpeedButton;
    SpeedButton2: TSpeedButton;
    SpeedButton3: TSpeedButton;
    SpeedButton4: TSpeedButton;
    Label13: TLabel;
    tbs_Players: TTabSheet;
    tbs_Tournaments: TTabSheet;
    Panel7: TPanel;
    Panel2: TPanel;
    Label3: TLabel;
    stg_TournamentTables: TStringGrid;
    Panel32: TPanel;
    btn_EditTourTables: TSpeedButton;
    Label16: TLabel;
    img_AlertTables: TImage;
    Panel6: TPanel;
    Panel17: TPanel;
    stg_TournamentRounds: TStringGrid;
    Panel18: TPanel;
    SpeedButton9: TSpeedButton;
    SpeedButton10: TSpeedButton;
    SpeedButton12: TSpeedButton;
    Label15: TLabel;
    img_AlertRounds: TImage;
    Panel15: TPanel;
    stg_Tournaments: TStringGrid;
    Panel16: TPanel;
    SpeedButton5: TSpeedButton;
    SpeedButton6: TSpeedButton;
    SpeedButton7: TSpeedButton;
    SpeedButton8: TSpeedButton;
    Label14: TLabel;
    chb_ShowOlder: TCheckBox;
    tbs_WinDistribution: TTabSheet;
    Panel9: TPanel;
    Panel19: TPanel;
    stg_WinDistribution: TStringGrid;
    Panel20: TPanel;
    SpeedButton13: TSpeedButton;
    SpeedButton14: TSpeedButton;
    SpeedButton15: TSpeedButton;
    SpeedButton16: TSpeedButton;
    Label17: TLabel;
    Panel11: TPanel;
    Panel10: TPanel;
    Panel23: TPanel;
    lbl_WinPercentageSum: TLabel;
    stg_WinPercentage: TStringGrid;
    Panel24: TPanel;
    SpeedButton21: TSpeedButton;
    SpeedButton22: TSpeedButton;
    SpeedButton23: TSpeedButton;
    SpeedButton24: TSpeedButton;
    Label19: TLabel;
    Panel25: TPanel;
    stg_WinNumPlayers: TStringGrid;
    Panel26: TPanel;
    SpeedButton25: TSpeedButton;
    SpeedButton26: TSpeedButton;
    SpeedButton27: TSpeedButton;
    SpeedButton28: TSpeedButton;
    Label18: TLabel;
    tbs_Reports: TTabSheet;
    Panel29: TPanel;
    lbl_ReportName: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    dtp_ReportFrom: TDateTimePicker;
    dtp_ReportTo: TDateTimePicker;
    btn_GetReportData: TButton;
    tbs_Login: TTabSheet;
    Panel46: TPanel;
    pnl_Login: TPanel;
    Image2: TImage;
    btn_LoginOK: TSpeedButton;
    edt_Password: TLabeledEdit;
    edt_Username: TLabeledEdit;
    tbs_Blank: TTabSheet;
    tbs_Settings: TTabSheet;
    GroupBox1: TGroupBox;
    edt_DatabaseUser: TLabeledEdit;
    edt_DatabasePass: TLabeledEdit;
    edt_Database: TLabeledEdit;
    btn_Save: TButton;
    GroupBox2: TGroupBox;
    edt_WebCamDeviceId: TLabeledEdit;
    Button5: TButton;
    chb_WebCamInUse: TCheckBox;
    GroupBox3: TGroupBox;
    Label20: TLabel;
    edt_Currency_Symbol: TLabeledEdit;
    Button6: TButton;
    com_Language: TComboBox;
    GroupBox4: TGroupBox;
    img_LogoSettings: TImage;
    Button7: TButton;
    Button8: TButton;
    GroupBox5: TGroupBox;
    Button9: TButton;
    edt_DisplaySeatingTime: TLabeledEdit;
    edt_DisplayRegisteringTime: TLabeledEdit;
    tbs_Profiles: TTabSheet;
    Panel12: TPanel;
    Panel27: TPanel;
    stg_Profiles: TStringGrid;
    Panel28: TPanel;
    SpeedButton29: TSpeedButton;
    SpeedButton30: TSpeedButton;
    SpeedButton31: TSpeedButton;
    SpeedButton32: TSpeedButton;
    Label2: TLabel;
    tbs_CashGames: TTabSheet;
    Panel33: TPanel;
    stg_CashGames: TStringGrid;
    Panel34: TPanel;
    SpeedButton35: TSpeedButton;
    SpeedButton36: TSpeedButton;
    SpeedButton37: TSpeedButton;
    SpeedButton38: TSpeedButton;
    Label21: TLabel;
    Panel35: TPanel;
    Panel36: TPanel;
    Label22: TLabel;
    stg_CashGameTables: TStringGrid;
    Panel37: TPanel;
    edt_CashGameTables: TSpeedButton;
    Label23: TLabel;
    Panel38: TPanel;
    Panel39: TPanel;
    Panel40: TPanel;
    tbs_RoundTypes: TTabSheet;
    Panel41: TPanel;
    stg_RoundTypeRounds: TStringGrid;
    Panel42: TPanel;
    SpeedButton40: TSpeedButton;
    SpeedButton41: TSpeedButton;
    SpeedButton42: TSpeedButton;
    Label8: TLabel;
    Panel43: TPanel;
    Panel44: TPanel;
    stg_RoundTypes: TStringGrid;
    Panel45: TPanel;
    SpeedButton44: TSpeedButton;
    SpeedButton45: TSpeedButton;
    SpeedButton46: TSpeedButton;
    SpeedButton47: TSpeedButton;
    Label24: TLabel;
    tbs_CageCashGame: TTabSheet;
    tbs_Hall: TTabSheet;
    tmr_RefreshHall: TTimer;
    tbs_Countries: TTabSheet;
    pnl_SubjectImage: TPanel;
    img_Country: TImage;
    Label25: TLabel;
    btn_ChangePicture: TButton;
    btn_DeletePicture: TButton;
    Panel47: TPanel;
    stg_Countries: TStringGrid;
    Panel48: TPanel;
    SpeedButton11: TSpeedButton;
    SpeedButton33: TSpeedButton;
    SpeedButton43: TSpeedButton;
    Label26: TLabel;
    btn_MenuCountries: TSpeedButton;
    btn_MenuDrinks: TSpeedButton;
    tbs_Drinks: TTabSheet;
    Panel49: TPanel;
    stg_Drinks: TStringGrid;
    Panel50: TPanel;
    SpeedButton39: TSpeedButton;
    SpeedButton48: TSpeedButton;
    SpeedButton49: TSpeedButton;
    Label27: TLabel;
    act_Drinks: TAction;
    act_Countries: TAction;
    act_RoundTypes: TAction;
    act_Hall: TAction;
    Image1: TImage;
    img_AlertCashTables: TImage;
    btn_MenuDrinkOrders: TSpeedButton;
    tbs_DrinkOrders: TTabSheet;
    Panel51: TPanel;
    Panel52: TPanel;
    Label28: TLabel;
    GroupBox6: TGroupBox;
    btn_ArchiveOldData: TButton;
    Panel53: TPanel;
    Panel54: TPanel;
    stg_TableZones: TStringGrid;
    Panel55: TPanel;
    SpeedButton50: TSpeedButton;
    SpeedButton51: TSpeedButton;
    SpeedButton52: TSpeedButton;
    SpeedButton53: TSpeedButton;
    Label29: TLabel;
    btn_MenuEMailing: TSpeedButton;
    tbs_EMailing: TTabSheet;
    Button1: TButton;
    GroupBox7: TGroupBox;
    dtp_GDTimeStart: TDateTimePicker;
    Button10: TButton;
    XMLDocument1: TXMLDocument;
    stg_GridReport: TDBGrid;
    DataSourceReport: TDataSource;
    OracleDataSetReport: TOracleDataSet;
    tbs_TournamentTypes: TTabSheet;
    Panel56: TPanel;
    stg_TournamentTypes: TStringGrid;
    Panel57: TPanel;
    SpeedButton54: TSpeedButton;
    SpeedButton55: TSpeedButton;
    SpeedButton56: TSpeedButton;
    Label6: TLabel;
    btn_TournamentTypes: TSpeedButton;
    act_TournamentTypes: TAction;
    btn_ReportCashGame: TSpeedButton;
    act_CashGameReport: TAction;
    pnl_ReportDetail: TPanel;
    Panel59: TPanel;
    stg_ReportDetail: TDBGrid;
    DataSourceReportDetail: TDataSource;
    OracleDataSetReportDetail: TOracleDataSet;
    btn_DrinkOrders: TSpeedButton;
    act_Bar: TAction;
    Panel58: TPanel;
    stg_ReleasedDrinks: TStringGrid;
    stg_DrinkOrders: TStringGrid;
    btn_ReportDrinkOrders: TSpeedButton;
    tbs_RakeValues: TTabSheet;
    btn_RakeValues: TSpeedButton;
    Panel60: TPanel;
    Panel61: TPanel;
    Panel62: TPanel;
    Panel63: TPanel;
    Panel64: TPanel;
    stg_RakeValues: TStringGrid;
    Panel65: TPanel;
    SpeedButton61: TSpeedButton;
    SpeedButton62: TSpeedButton;
    SpeedButton63: TSpeedButton;
    SpeedButton64: TSpeedButton;
    Label30: TLabel;
    Panel66: TPanel;
    Panel67: TPanel;
    stg_Rakes: TStringGrid;
    Panel68: TPanel;
    SpeedButton65: TSpeedButton;
    SpeedButton66: TSpeedButton;
    SpeedButton67: TSpeedButton;
    SpeedButton68: TSpeedButton;
    Label31: TLabel;
    stg_Rake: TStringGrid;
    Label7: TLabel;
    btn_CloseCage: TSpeedButton;
    btn_CasinoInventory: TSpeedButton;
    tbs_CasinoInventory: TTabSheet;
    Panel69: TPanel;
    stg_CasinoInventory: TStringGrid;
    Panel70: TPanel;
    SpeedButton57: TSpeedButton;
    SpeedButton58: TSpeedButton;
    SpeedButton59: TSpeedButton;
    SpeedButton60: TSpeedButton;
    Label10: TLabel;
    btn_ReportEvents: TSpeedButton;
    btn_ReportDealerActivity: TSpeedButton;
    GroupBox8: TGroupBox;
    btn_UpdateAppInDB: TButton;
    Panel21: TPanel;
    stg_Privileges: TStringGrid;
    Panel22: TPanel;
    btn_EditProfiles: TSpeedButton;
    Label32: TLabel;
    Panel5: TPanel;
    stg_ProfilesFilter: TStringGrid;
    Panel30: TPanel;
    SpeedButton18: TSpeedButton;
    Label11: TLabel;
    btn_Reprint: TButton;
    XPManifest1: TXPManifest;
    ClientSocket1: TClientSocket;
    Panel71: TPanel;
    stg_DrinkTypes: TStringGrid;
    Panel72: TPanel;
    SpeedButton17: TSpeedButton;
    SpeedButton19: TSpeedButton;
    SpeedButton20: TSpeedButton;
    Label33: TLabel;
    img_Inspector: TImage;
    img_Barman: TImagePanel;
    Panel73: TPanel;
    stg_LoginForms: TStringGrid;
    Panel74: TPanel;
    SpeedButton69: TSpeedButton;
    Label34: TLabel;
    Panel75: TPanel;
    btn_OrderDrink: TSpeedButton;
    procedure FormCreate(Sender: TObject);
    procedure Close1Click(Sender: TObject);
    procedure btn_ChangePictureClick(Sender: TObject);
    procedure btn_DeletePictureClick(Sender: TObject);
    procedure btn_GetReportDataClick(Sender: TObject);
    procedure btn_LoginCloseClick(Sender: TObject);
    procedure btn_MenuUsersClick(Sender: TObject);
    procedure btn_MenuReportClick(Sender: TObject);
    procedure btn_MenuTicketsClick(Sender: TObject);
    procedure btn_MenuPlayersClick(Sender: TObject);
    procedure act_UsersExecute(Sender: TObject);
    procedure act_TablesExecute(Sender: TObject);
    procedure act_PlayersExecute(Sender: TObject);
    procedure act_ProfilesExecute(Sender: TObject);
    procedure act_TournamentReportsExecute(Sender: TObject);
    procedure act_PrepareTournamentExecute(Sender: TObject);
    procedure act_WinDistributionExecute(Sender: TObject);
    procedure act_TicketsExecute(ASender: TObject);
    procedure ActionList1Execute(Action: TBasicAction; var Handled: Boolean);
    procedure act_SettingsExecute(Sender: TObject);
    procedure act_LoginExecute(Sender: TObject);
    procedure btn_LoginOKClick(Sender: TObject);
    procedure btn_PhotoFromWebCamClick(Sender: TObject);
    procedure act_CanChangePasswordExecute(Sender: TObject);
    procedure ChangePassword1Click(Sender: TObject);
    procedure btn_CloseClick(Sender: TObject);
    procedure act_PlayerPointsExecute(Sender: TObject);
    procedure act_DataTrackingExecute(Sender: TObject);
    procedure act_UserAccessExecute(Sender: TObject);
    procedure chb_GroupByPlayersClick(Sender: TObject);
    procedure btn_SaveClick(Sender: TObject);
    procedure About1Click(Sender: TObject);
    procedure stg_UsersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_TournamentsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_WinDistributionSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_WinNumPlayersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_ProfilesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure btn_NewClick(Sender: TObject);
    procedure btn_EditClick(Sender: TObject);
    procedure btn_DuplicateClick(Sender: TObject);
    procedure btn_DeleteClick(Sender: TObject);
    procedure SpeedButton1Click(Sender: TObject);
    procedure SpeedButton4Click(Sender: TObject);
    procedure SpeedButton2Click(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure SpeedButton13Click(Sender: TObject);
    procedure SpeedButton14Click(Sender: TObject);
    procedure SpeedButton15Click(Sender: TObject);
    procedure SpeedButton16Click(Sender: TObject);
    procedure SpeedButton25Click(Sender: TObject);
    procedure SpeedButton26Click(Sender: TObject);
    procedure SpeedButton27Click(Sender: TObject);
    procedure SpeedButton28Click(Sender: TObject);
    procedure SpeedButton21Click(Sender: TObject);
    procedure SpeedButton22Click(Sender: TObject);
    procedure SpeedButton23Click(Sender: TObject);
    procedure SpeedButton24Click(Sender: TObject);
    procedure SpeedButton5Click(Sender: TObject);
    procedure SpeedButton6Click(Sender: TObject);
    procedure SpeedButton7Click(Sender: TObject);
    procedure SpeedButton8Click(Sender: TObject);
    procedure SpeedButton9Click(Sender: TObject);
    procedure SpeedButton10Click(Sender: TObject);
    procedure SpeedButton11Click(Sender: TObject);
    procedure SpeedButton12Click(Sender: TObject);
    procedure Login1Click(Sender: TObject);
    procedure SpeedButton29Click(Sender: TObject);
    procedure SpeedButton30Click(Sender: TObject);
    procedure SpeedButton31Click(Sender: TObject);
    procedure SpeedButton32Click(Sender: TObject);
    procedure stg_WinPercentageSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_TournamentRoundsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure Button6Click(Sender: TObject);
    procedure tbs_LoginShow(Sender: TObject);
    procedure btn_EditProfilesClick(Sender: TObject);
    procedure SpeedButton34Click(Sender: TObject);
    procedure btn_EditTourTablesClick(Sender: TObject);
    procedure btn_LogoutClick(Sender: TObject);
    procedure ddd1Click(Sender: TObject);
    procedure edt_PasswordKeyPress(Sender: TObject; var Key: Char);
    procedure ApplicationEvents1Exception(Sender: TObject; E: Exception);
    procedure chb_ShowOlderClick(Sender: TObject);
    procedure stg_TournamentsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure act_TicketsCashGameExecute(Sender: TObject);
    procedure act_TicketsTournamentExecute(Sender: TObject);
    procedure Button9Click(Sender: TObject);
    procedure act_GeneralExecute(Sender: TObject);
    procedure btn_MenuGeneralClick(Sender: TObject);
    procedure btn_MenuPrepareTournamentClick(Sender: TObject);
    procedure act_PrepareCashGameExecute(Sender: TObject);
    procedure SpeedButton35Click(Sender: TObject);
    procedure SpeedButton36Click(Sender: TObject);
    procedure SpeedButton37Click(Sender: TObject);
    procedure SpeedButton38Click(Sender: TObject);
    procedure stg_CashGameTablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_UsersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_UserProfilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TournamentRoundsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TournamentTablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_WinDistributionDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_WinNumPlayersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_WinPercentageDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_ProfilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_PrivilegesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TournamentTablesClick(Sender: TObject);
    procedure stg_PrivilegesClick(Sender: TObject);
    procedure stg_GridReportDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_PlayerFromBreakTableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TableForBreakingDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_ProfilesClick(Sender: TObject);
    procedure edt_UsernameKeyPress(Sender: TObject; var Key: Char);
    procedure tbs_CageTournamentShow(Sender: TObject);
    procedure tbs_CageTournamentHide(Sender: TObject);
    procedure tmr_AlertTimer(Sender: TObject);
    procedure SpeedButton44Click(Sender: TObject);
    procedure SpeedButton45Click(Sender: TObject);
    procedure SpeedButton46Click(Sender: TObject);
    procedure SpeedButton47Click(Sender: TObject);
    procedure stg_RoundTypesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_RoundTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure SpeedButton40Click(Sender: TObject);
    procedure SpeedButton41Click(Sender: TObject);
    procedure SpeedButton42Click(Sender: TObject);
    procedure edt_CashGameTablesClick(Sender: TObject);
    procedure stg_CashGamesDblClick(Sender: TObject);
    procedure stg_CashGamesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure tmr_RefreshHallTimer(Sender: TObject);
    procedure stg_CashGamesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure SpeedButton33Click(Sender: TObject);
    procedure SpeedButton43Click(Sender: TObject);
    procedure stg_CountriesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_CountriesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_CountriesClick(Sender: TObject);
    procedure stg_TournamentsDblClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure SpeedButton39Click(Sender: TObject);
    procedure SpeedButton48Click(Sender: TObject);
    procedure SpeedButton49Click(Sender: TObject);
    procedure act_DrinksExecute(Sender: TObject);
    procedure act_CountriesExecute(Sender: TObject);
    procedure act_RoundTypesExecute(Sender: TObject);
    procedure act_HallExecute(Sender: TObject);
    procedure stg_DrinksDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_DrinksClick(Sender: TObject);
    procedure stg_DrinksSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure FormResize(Sender: TObject);
    procedure btn_MenuDrinkOrdersClick(Sender: TObject);
    procedure stg_DrinkOrdersDblClick(Sender: TObject);
    procedure stg_DrinkOrdersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure btn_ArchiveOldDataClick(Sender: TObject);
    procedure SpeedButton50Click(Sender: TObject);
    procedure SpeedButton51Click(Sender: TObject);
    procedure SpeedButton52Click(Sender: TObject);
    procedure SpeedButton53Click(Sender: TObject);
    procedure btn_MenuEMailingClick(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button10Click(Sender: TObject);
    procedure Print1Click(Sender: TObject);
    procedure stg_GridReportTitleClick(Column: TColumn);
    procedure stg_GridReportMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
    procedure SpeedButton54Click(Sender: TObject);
    procedure SpeedButton55Click(Sender: TObject);
    procedure SpeedButton56Click(Sender: TObject);
    procedure act_TournamentTypesExecute(Sender: TObject);
    procedure stg_TournamentTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_TournamentTypesClick(Sender: TObject);
    procedure act_CashGameReportExecute(Sender: TObject);
    procedure stg_GridReportCellClick(Column: TColumn);
    procedure tbs_ReportsResize(Sender: TObject);
    procedure stg_GridReportMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
    procedure stg_GridReportMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
    procedure btn_DrinkOrdersClick(Sender: TObject);
    procedure stg_ReportDetailTitleClick(Column: TColumn);
    procedure stg_GridReportDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure btn_ReportDrinkOrdersClick(Sender: TObject);
    procedure btn_RakeValuesClick(Sender: TObject);
    procedure stg_RakesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure SpeedButton65Click(Sender: TObject);
    procedure SpeedButton66Click(Sender: TObject);
    procedure SpeedButton67Click(Sender: TObject);
    procedure SpeedButton68Click(Sender: TObject);
    procedure stg_RakesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_RakeValuesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure SpeedButton61Click(Sender: TObject);
    procedure SpeedButton62Click(Sender: TObject);
    procedure SpeedButton63Click(Sender: TObject);
    procedure SpeedButton64Click(Sender: TObject);
    procedure stg_RakeValuesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_RakeDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_TournamentsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure stg_RakesClick(Sender: TObject);
    procedure btn_CloseCageClick(Sender: TObject);
    procedure btn_CasinoInventoryClick(Sender: TObject);
    procedure SpeedButton57Click(Sender: TObject);
    procedure stg_CasinoInventoryClick(Sender: TObject);
    procedure stg_CasinoInventoryDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure SpeedButton58Click(Sender: TObject);
    procedure SpeedButton59Click(Sender: TObject);
    procedure SpeedButton60Click(Sender: TObject);
    procedure stg_CasinoInventorySelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure btn_ReportEventsClick(Sender: TObject);
    procedure btn_ReportDealerActivityClick(Sender: TObject);
    procedure btn_UpdateAppInDBClick(Sender: TObject);
    procedure stg_ProfilesFilterSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure stg_ProfilesFilterDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_ProfilesFilterClick(Sender: TObject);
    procedure btn_ReprintClick(Sender: TObject);
    procedure SpeedButton17Click(Sender: TObject);
    procedure SpeedButton19Click(Sender: TObject);
    procedure SpeedButton20Click(Sender: TObject);
    procedure stg_DrinkTypesClick(Sender: TObject);
    procedure stg_DrinkTypesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure stg_DrinkTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
    procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
    procedure ClientSocket1Disconnect(Sender: TObject; Socket: TCustomWinSocket);
    procedure img_BarmanClick(Sender: TObject);
    procedure SpeedButton69Click(Sender: TObject);
    procedure btn_OrderDrinkClick(Sender: TObject);
    procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
    procedure stg_GridReportKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
  private
    LoggedUserId: string;
    ComputerName: array [0 .. 256] of Char;
    ConnectedToDB, CanSelect: Boolean;
    PrevTournamentRow: Integer;
    CopyRoundToTournament: Boolean;
    m_OrigTournamentID, QueryReport: string;
    ReportAscDesc: string;
    PrevGridSearchTime: double;
    procedure ShowTabSheet(TabSheet: TTabSheet);
    procedure HideAllTabs();
    procedure ShowRightFormsForUserPrivileges(UserID: string);
    procedure CloseApplication();
    procedure HideAllDetailButtons(Sender: TObject);
    procedure GetIniFile();
    procedure SaveToErrLog(ErrorMsg: string);
    procedure DBGridFormatNumber(Sender: TField; var Text: string; DisplayText: Boolean);
    procedure GetLoggedBarman();

    { Private declarations }
  public
    { Public declarations }
    EditFieldColor: TColor;
    m_FrmHall: TFrmHall;
    MainUtils: TMainUtils;
    FraPlayersMain: TFraPlayers;
    OrderReportBy: string;
    SearchGridStr: string;
    function CheckCageOpened(): Boolean;
    procedure SelectGridRow(Grid: TStringGrid; SelRow: Integer);
    procedure SumWinPercentage();
    procedure SavePhotoToDB(PhotoSource, FileExt, ObjectID: string; Resize: Boolean = true);
    procedure GetGridData(Grid: TStringGrid; Query: string; AutoSizeGrid: Boolean);
    procedure SetGridData(stg_GridData: TStringGrid; OracleQuery: TOracleQuery; AutoSizeGrid: Boolean = false);
    procedure CloneTournamentRounds(FromTournamentID, ToTournamentID: string; FromRoundTypes, ToRoundTypes: Boolean);
    function CheckSoldTicketForTournament(TournamentID: string): Boolean;
    procedure GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
    procedure SetActiveSubMenuButton(Sender: TObject);
    procedure ShowCAMphotoForm(SubjectID: string);
    procedure UpdateRebuyOrAddon(IsCashGame, IsRebuy: Boolean; TicketID, Value: string);
    function SearchStringGrid(Grid: TStringGrid; TextVal: string; GridRow: Integer = -1): Integer; // row
    function GetCharFromVirtualKey(Key: Word): string;
    procedure SendEventToServer(EventType, TournamentID, TableID: string);

  type
    THackDBGrid = class(TDBGrid);

    const
      GridGreenColor: TColor = $0095FF98;
      GridSelGreenColor: TColor = $0000BB46;
      LanguageEnglish: string = 'en';
      LanguageSlovensko: string = 'sl_SI';
      LanguageItaliano: string = 'it_IT';
    end;

  var
    FrmMain: TFrmMain;

  type
    TGridHack = class(TCustomGrid);

implementation

uses EditDrinkTypes;
{$R *.dfm}

procedure TFrmMain.SendEventToServer(EventType, TournamentID, TableID: string);
begin
  try
    if not ClientSocket1.Active then
    begin
      ClientSocket1.Open;
      if ParamStr(3) <> 'LOGIN' then
        ClientSocket1.Active := true;
    end;
  finally
    ClientSocket1.Socket.SendText(EventType + '|1|' + TournamentID + '|2|' + TableID);
  end;
end;

procedure TFrmMain.SelectGridRow(Grid: TStringGrid; SelRow: Integer);
var
  GridRect: TGridRect;
begin
  if SelRow >= Grid.FixedRows then
  begin
    if Grid.RowCount < SelRow then
      SelRow := Grid.RowCount;
    GridRect.Top := SelRow;
    GridRect.Bottom := SelRow;
    GridRect.Left := 0;
    GridRect.Right := Grid.ColCount - 1;
    Grid.Selection := GridRect;
    // select cell
    Grid.Row := SelRow;
    { if (Grid.RowCount > Grid.VisibleRowCount) then
      begin
      if SelRow = Grid.FixedRows then
      Grid.TopRow := SelRow
      else
      Grid.TopRow := SelRow - 1;
      end; }
  end;
end;

procedure TFrmMain.SetGridData(stg_GridData: TStringGrid; OracleQuery: TOracleQuery; AutoSizeGrid: Boolean);
var
  c, r: Integer;
  FieldName, DataValue: string;
begin
  for c := 0 to stg_GridData.ColCount - 1 do
  begin
    for r := 0 to stg_GridData.RowCount - 1 do
    begin
      stg_GridData.Cells[c, r] := '';
    end;
  end;
  stg_GridData.ColCount := OracleQuery.FieldCount;
  stg_GridData.ColWidths[0] := -1;
  // ORIGINAL TABLE FIELD NAMES - ROW=0
  for c := 0 to OracleQuery.FieldCount - 1 do
  begin
    stg_GridData.Cells[c, 0] := OracleQuery.FieldName(c);
  end;
  // TRANSLATED TABLE FIELD NAMES - ROW=1
  for c := 0 to OracleQuery.FieldCount - 1 do
  begin
    FieldName := OracleQuery.FieldName(c);
    stg_GridData.Cells[c, 1] := MainUtils.GetFieldNameText(FieldName);
  end;
  r := 2;
  while not OracleQuery.Eof do
  begin
    for c := 0 to stg_GridData.ColCount - 1 do
    begin
      DataValue := OracleQuery.Field(c);
      stg_GridData.Cells[c, r] := DataValue;
    end;
    inc(r);
    OracleQuery.Next;
  end;
  // stg_GridData.RowCount := r;
  if r = 2 then
  begin
    stg_GridData.RowCount := 3;
  end
  else
  begin
    stg_GridData.RowCount := r;
  end;
  stg_GridData.FixedRows := 2;
  stg_GridData.RowHeights[0] := -1;
  if AutoSizeGrid then
  begin
    for c := 1 to stg_GridData.ColCount - 1 do
    begin
      stg_GridData.ColWidths[c] := (stg_GridData.Width - 3) div (stg_GridData.ColCount - 1);
    end;
  end;
end;

procedure TFrmMain.GetGridData(Grid: TStringGrid; Query: string; AutoSizeGrid: Boolean);
var
  c, r, SelRow: Integer;
  WhereCond: string;
begin
  if Query <> '' then
  begin
    FrmMain.OracleQuery1.SQL.Clear;
    OracleQuery1.Variables.List.Clear;
    if Query = uSQLs.SQL_Tournaments then
    begin
      WhereCond := '';
      if not chb_ShowOlder.Checked then
      begin
        WhereCond := 'and trunc(event_start)>=trunc((select sysdate from dual))';
      end;
      OracleQuery1.DeclareAndSet(':DATA', otVarchar2, WhereCond);
    end;
    FrmMain.OracleQuery1.SQL.Text := (Query);
    FrmMain.OracleQuery1.Execute;
    SelRow := Grid.Row;
    SetGridData(Grid, FrmMain.OracleQuery1, AutoSizeGrid);
    SelectGridRow(Grid, SelRow);
    Grid.Refresh;
  end
  else
  begin
    for c := 0 to Grid.ColCount - 1 do
    begin
      for r := 0 to Grid.RowCount - 1 do
      begin
        Grid.Cells[c, r] := '';
      end;
    end;
  end;
end;

procedure TFrmMain.chb_GroupByPlayersClick(Sender: TObject);
begin
  btn_GetReportData.Click;
end;

procedure TFrmMain.chb_ShowOlderClick(Sender: TObject);
begin
  GetGridData(stg_Tournaments, SQL_Tournaments, false);
  stg_TournamentsSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.Close1Click(Sender: TObject);
begin
  CloseApplication();
end;

procedure TFrmMain.FormCreate(Sender: TObject);
var
  i: DWord;
begin
  ClientSocket1.Port := 7781;
  ClientSocket1.Host := 'localhost';
  if ParamStr(3) <> 'LOGIN' then
    ClientSocket1.Active := true;
  height := 768;
  Width := 1024;
  CopyRoundToTournament := false;
  EditFieldColor := $00DFE7D3;
  HideAllTabs();
  GetIniFile();
  com_Language.Items.Add(LanguageEnglish);
  com_Language.Items.Add(LanguageSlovensko);
  com_Language.Items.Add(LanguageItaliano);
  img_Barman.Image.OnClick := img_BarmanClick;
  img_Barman.PlayerStatus.OnClick := img_BarmanClick;
  img_Barman.PlayerName.OnClick := img_BarmanClick;
  stg_Profiles.ColWidths[1] := 250;
  // ------
  // language
  gnugettext.TranslateComponent(self);
  MainUtils := TMainUtils.Create();
  uUtils.pct_Temp := TPicture.Create();
  pnl_MainMenu.Visible := false;
  i := 256;
  Windows.GetComputerName(ComputerName, i);
  //
  // CLOCK
  //
  if ParamStr(1) <> '' then
  begin
    pgc_Main.ActivePage := tbs_Login;
    edt_Username.Text := ParamStr(1);
    edt_Password.Text := ParamStr(2);
    if (ParamStr(3) = 'LOGIN') then
    begin
      btn_LoginOK.Click;
      WindowState := wsNormal;
    end
  end
  else
  begin
    pgc_Main.ActivePage := tbs_Login;
  end;
end;

procedure TFrmMain.FormDestroy(Sender: TObject);
begin
  FreeAndNil(uUtils.pct_Temp);
  FreeAndNil(MainUtils);
  ClientSocket1.Active := false;
end;

procedure TFrmMain.FormResize(Sender: TObject);
begin
  LockWindowUpdate(self.handle);
  LockWindowUpdate(0);
end;

procedure TFrmMain.ShowCAMphotoForm(SubjectID: string);
begin
  if SubjectID = '' then
  begin
    ShowMessage(_('First select subject!'));
  end
  else
  begin
    if FrmCameraGetImage = nil then
    begin
      if FrmMain.chb_WebCamInUse.Checked then
      begin
        Application.CreateForm(TFrmCameraGetImage, FrmCameraGetImage);
        FrmCameraGetImage.ShowForm(SubjectID);
      end
      else
      begin
        ShowMessage(_('Configure settings for Web Camera using!'));
      end;
    end
    else
    begin
      FrmCameraGetImage.ShowForm(SubjectID);
    end;
  end;
end;

procedure TFrmMain.ShowRightFormsForUserPrivileges(UserID: string);
var
  j: Integer;
  ActionPrivilege: string;
  AComponent: TComponent;
begin
  // disable ALL ACTIONS
  for j := 0 to ActionList1.ActionCount - 1 do
  begin
    AComponent := FindComponent(ActionList1.Actions[j].Name);
    if AComponent <> nil then
    begin
      TAction(AComponent).Visible := false;
      TAction(AComponent).Enabled := false;
    end;
  end;
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('select P.NAME from USER_HAS_PROFILE uhp join PROFILE_HAS_PRIVILEGE PHP ON PHP.PROFILE_ID=UHP.PROFILE_ID join PRIVILEGE P ON P.ID=PHP.PRIVILEGE_ID where UHP.USER_ID=' +
      LoggedUserId + ' ORDER BY P.NAME');
  OracleQuery1.Execute;
  // enable user actions
  while not OracleQuery1.Eof do
  begin
    begin
      ActionPrivilege := OracleQuery1.Field(0);
      for j := 0 to ActionList1.ActionCount - 1 do
      begin
        if pos(ActionPrivilege, ActionList1.Actions[j].Name) > 0 then
        begin
          AComponent := FindComponent(ActionList1.Actions[j].Name);
          if AComponent <> nil then
          begin
            TAction(AComponent).Visible := true;
            TAction(AComponent).Enabled := true;
          end;
        end;
      end;
      OracleQuery1.Next;
    end;
  end;
  // ----
  FrmMain.Menu := MainMenu;
  pnl_MainMenu.Visible := true;
  pgc_Main.ActivePage := tbs_Blank;
end;

procedure TFrmMain.ShowTabSheet(TabSheet: TTabSheet);
begin
  pgc_Main.ActivePage := TabSheet;
  pgc_Main.ActivePage.Caption := TabSheet.Caption;
end;

procedure TFrmMain.SpeedButton10Click(Sender: TObject);
begin
  uFrmEditTournamentRounds.ShowForm(true, false, stg_TournamentRounds.Cells[0, stg_TournamentRounds.Row]);
end;

procedure TFrmMain.SpeedButton11Click(Sender: TObject);
begin
  uFrmEditCountries.ShowForm(false, false, stg_Countries.Cells[0, stg_Countries.Row]);
end;

procedure TFrmMain.SpeedButton12Click(Sender: TObject);
begin
  if MessageDlg(_('Delete last sequence?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    if CheckSoldTicketForTournament(stg_Tournaments.Cells[0, stg_Tournaments.Row]) then
    begin
      MessageDlg(_('Cannot be deleted. Tickets are sold for this tournament.'), mtInformation, [mbOK], 0);
    end
    else
    begin
      DeleteDataFromDB('TOURNAMENT_ROUNDS', 'ID=(SELECT MAX(ID) FROM TOURNAMENT_ROUNDS WHERE TOURNAMENT_ID=' + stg_Tournaments.Cells[0, stg_Tournaments.Row] + ')');
      GetGridData(stg_TournamentRounds, SQL_TournamentRounds + stg_Tournaments.Cells[0, stg_Tournaments.Row] + ' ORDER BY SEQ_INDEX ASC', false);
    end;
  end;
end;

procedure TFrmMain.SpeedButton13Click(Sender: TObject);
begin
  uFrmEditWinDist.ShowForm(false, false, stg_WinDistribution.Cells[0, stg_WinDistribution.Row]);
end;

procedure TFrmMain.SpeedButton14Click(Sender: TObject);
begin
  uFrmEditWinDist.ShowForm(true, false, stg_WinDistribution.Cells[0, stg_WinDistribution.Row]);
end;

procedure TFrmMain.SpeedButton15Click(Sender: TObject);
begin
  uFrmEditWinDist.ShowForm(true, true, stg_WinDistribution.Cells[0, stg_WinDistribution.Row]);
end;

procedure TFrmMain.SpeedButton16Click(Sender: TObject);
begin
  try
    if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      DeleteDataFromDB('WIN_DISTRIBUTION', 'ID=' + stg_WinDistribution.Cells[0, stg_WinDistribution.Row]);
      GetGridData(stg_WinDistribution, SQL_WinDist, true);
    end;
  except
    on E: Exception do
    begin
      ShowMessage(_('Record have bounded Number of player!'));
    end;
  end;
end;

procedure TFrmMain.SpeedButton17Click(Sender: TObject);
begin
  uFrmEditDrinkTypes.ShowForm(false, false, stg_DrinkTypes.Cells[0, stg_DrinkTypes.Row]);
end;

procedure TFrmMain.SpeedButton19Click(Sender: TObject);
begin
  uFrmEditDrinkTypes.ShowForm(true, false, stg_DrinkTypes.Cells[0, stg_DrinkTypes.Row]);
end;

procedure TFrmMain.SpeedButton1Click(Sender: TObject);
begin
  uFrmEdittables.ShowForm(false, false, stg_Tables.Cells[0, stg_Tables.Row]);
end;

procedure TFrmMain.SpeedButton20Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('DRINK_TYPES', 'ID=' + stg_DrinkTypes.Cells[0, stg_DrinkTypes.Row]);
    GetGridData(stg_DrinkTypes, SQL_DrinkTypes, false);
  end;
end;

procedure TFrmMain.SpeedButton21Click(Sender: TObject);
begin
  uFrmEditWinPercentage.ShowForm(false, false, stg_WinPercentage.Cells[0, stg_WinPercentage.Row]);
end;

procedure TFrmMain.SpeedButton22Click(Sender: TObject);
begin
  uFrmEditWinPercentage.ShowForm(true, false, stg_WinPercentage.Cells[0, stg_WinPercentage.Row]);
end;

procedure TFrmMain.SpeedButton23Click(Sender: TObject);
begin
  uFrmEditWinPercentage.ShowForm(true, true, stg_WinPercentage.Cells[0, stg_WinPercentage.Row]);
end;

procedure TFrmMain.SpeedButton24Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('WIN_PERCENTAGE', 'ID=' + stg_WinPercentage.Cells[0, stg_WinPercentage.Row]);
    GetGridData(stg_WinPercentage, SQL_WinPerc + stg_WinNumPlayers.Cells[0, stg_WinNumPlayers.Row], true);
    SumWinPercentage();
  end;
end;

procedure TFrmMain.stg_RakeValuesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_RakeValuesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  stg_RakeValues.Refresh;
end;

procedure TFrmMain.SumWinPercentage();
var
  ProcentVal: string;
begin
  ProcentVal := SumColGridData(FrmMain.stg_WinPercentage, 2, 2, FrmMain.stg_WinPercentage.RowCount);
  if pos('100', ProcentVal) > 0 then
    FrmMain.lbl_WinPercentageSum.Font.Color := clGreen
  else
    FrmMain.lbl_WinPercentageSum.Font.Color := clRed;
  FrmMain.lbl_WinPercentageSum.Caption := _('Total Percentage:') + ' ' + ProcentVal + ' %';
end;

procedure TFrmMain.SpeedButton25Click(Sender: TObject);
begin
  uFrmEditWinNumPlayers.ShowForm(false, false, stg_WinNumPlayers.Cells[0, stg_WinNumPlayers.Row]);
end;

procedure TFrmMain.SpeedButton26Click(Sender: TObject);
begin
  uFrmEditWinNumPlayers.ShowForm(true, false, stg_WinNumPlayers.Cells[0, stg_WinNumPlayers.Row]);
end;

procedure TFrmMain.SpeedButton27Click(Sender: TObject);
begin
  uFrmEditWinNumPlayers.ShowForm(true, true, stg_WinNumPlayers.Cells[0, stg_WinNumPlayers.Row]);
end;

procedure TFrmMain.SpeedButton28Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('WIN_PLAYERS_NUMBER', 'ID=' + stg_WinNumPlayers.Cells[0, stg_WinNumPlayers.Row]);
    GetGridData(stg_WinNumPlayers, SQL_WinPlayersNum + stg_WinDistribution.Cells[0, stg_WinDistribution.Row], true);
  end;
end;

procedure TFrmMain.SpeedButton29Click(Sender: TObject);
begin
  uFrmEditProfiles.ShowForm(false, false, stg_Profiles.Cells[0, stg_Profiles.Row]);
end;

procedure TFrmMain.SpeedButton2Click(Sender: TObject);
begin
  uFrmEdittables.ShowForm(true, false, stg_Tables.Cells[0, stg_Tables.Row]);
end;

procedure TFrmMain.SpeedButton30Click(Sender: TObject);
begin
  uFrmEditProfiles.ShowForm(true, false, stg_Profiles.Cells[0, stg_Profiles.Row]);
end;

procedure TFrmMain.SpeedButton31Click(Sender: TObject);
begin
  uFrmEditProfiles.ShowForm(true, true, stg_Profiles.Cells[0, stg_Profiles.Row]);
end;

procedure TFrmMain.SpeedButton32Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('PROFILES', 'ID=' + stg_Profiles.Cells[0, stg_Profiles.Row]);
    GetGridData(stg_Profiles, SQL_Profiles, true);
  end;
end;

procedure TFrmMain.SpeedButton33Click(Sender: TObject);
begin
  uFrmEditCountries.ShowForm(true, false, stg_Countries.Cells[0, stg_Countries.Row]);
end;

procedure TFrmMain.btn_EditProfilesClick(Sender: TObject);
begin
  if stg_Profiles.Cells[0, stg_Profiles.Row] <> '' then
  begin
    frm_SelectObjects.ShowSelectObjectsForm(stg_Privileges, true, 'PROFILES',
      'Select distinct(pr.ID), pr.NAME from PROFILE_HAS_PRIVILEGE php right join PRIVILEGE pr on pr.ID=php.PRIVILEGE_ID where pr.ID not in (select PRIVILEGE_ID from PROFILE_HAS_PRIVILEGE where PROFILE_ID ='
        + stg_Profiles.Cells[0, stg_Profiles.Row] + ') ORDER BY PR.NAME',
      'Select distinct(pr.ID), pr.NAME, pHP.ID AS PHPID from PROFILE_HAS_PRIVILEGE php join PRIVILEGE pr on pr.ID=php.PRIVILEGE_ID where php.PROFILE_ID =' + stg_Profiles.Cells[0, stg_Profiles.Row]
        + ' ORDER BY PR.NAME', stg_Profiles.Cells[0, stg_Profiles.Row]);
  end;
end;

procedure TFrmMain.SpeedButton34Click(Sender: TObject);
begin
  if stg_Users.Cells[0, stg_Users.Row] <> '' then
  begin
    frm_SelectObjects.ShowSelectObjectsForm(stg_UserProfiles, true, 'USERS',
      'Select distinct(up.ID), up.NAME from USER_HAS_PROFILE uhp right join PROFILES up on up.ID=uhp.PROFILE_ID where up.ID not in (select PROFILE_ID from USER_HAS_PROFILE where USER_ID =' +
        stg_Users.Cells[0, stg_Users.Row] + ') ORDER BY UP.NAME',
      'select distinct(uhp.ID), up.NAME, UHP.ID AS UHPID from USER_HAS_PROFILE uhp join PROFILES up on up.ID=uhp.PROFILE_ID where uhp.USER_ID =' + stg_Users.Cells[0, stg_Users.Row]
        + ' ORDER BY UP.NAME', stg_Users.Cells[0, stg_Users.Row]);
  end;
end;

procedure TFrmMain.SpeedButton35Click(Sender: TObject);
begin
  uFrmEditCashGames.ShowForm(false, false, stg_CashGames.Cells[0, stg_CashGames.Row]);
end;

procedure TFrmMain.SpeedButton36Click(Sender: TObject);
begin
  uFrmEditCashGames.ShowForm(true, false, stg_CashGames.Cells[0, stg_CashGames.Row]);
end;

procedure TFrmMain.SpeedButton37Click(Sender: TObject);
begin
  m_OrigTournamentID := stg_CashGames.Cells[0, stg_CashGames.Row];
  uFrmEditCashGames.ShowForm(true, true, stg_CashGames.Cells[0, stg_CashGames.Row]);
end;

procedure TFrmMain.SpeedButton38Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    begin
      DeleteDataFromDB('CASH_GAMES', 'ID=' + stg_CashGames.Cells[0, stg_CashGames.Row]);
      GetGridData(stg_CashGames, SQL_CashGames, false);
    end;
  end;
end;

procedure TFrmMain.SpeedButton39Click(Sender: TObject);
begin
  uFrmEditDrinks.ShowForm(false, false, stg_Drinks.Cells[0, stg_Drinks.Row]);
end;

procedure TFrmMain.btn_EditTourTablesClick(Sender: TObject);
var
  WhereCond: string;
begin
  if stg_TournamentRounds.Cells[0, 2] = '' then
  begin
    ShowMessage(_('First select rounds for tournament!'));
    exit;
  end;
  if stg_Tournaments.Cells[0, stg_Tournaments.Row] <> '' then
  begin
    WhereCond := stg_Tournaments.Cells[0, stg_Tournaments.Row];
    frm_SelectObjects.ShowSelectObjectsForm(stg_TournamentTables, true, 'TOURNAMENTS',
      'SELECT DISTINCT(TA.ID), TA.NAME FROM TABLES TA LEFT JOIN TOURNAMENT_TABLES TT ON TA.ID=TT.TABLE_ID' + ' WHERE (TA.ID NOT IN (SELECT TABLE_ID FROM TOURNAMENT_TABLES TT WHERE TOURNAMENT_ID IN' +
        ' (SELECT ID FROM GETTOURNAMENT_START_END_TIME X1' + ' WHERE X1.EVENT_START < (SELECT EVENT_END FROM GETTOURNAMENT_START_END_TIME WHERE ID=' + WhereCond +
        ' AND (STATUS<>''FINISHED'' OR STATUS IS NULL))' + ' AND  X1.EVENT_END > (SELECT EVENT_START FROM GETTOURNAMENT_START_END_TIME WHERE ID=' + WhereCond +
        ' AND (STATUS<>''FINISHED'' OR STATUS IS NULL))))) AND (TA.ID NOT IN (SELECT DISTINCT(TABLE_ID) FROM CASH_GAMES WHERE TABLE_ID IS NOT NULL))AND TA.CASH_GAME=0 ORDER BY NAME ASC',
      'select distinct(tables.id), tables.name, tournament_tables.id from tournament_tables, tables where tournament_tables.table_id = tables.id and tournament_id=' + stg_Tournaments.Cells
        [0, stg_Tournaments.Row] + ' ORDER BY TABLES.NAME', stg_Tournaments.Cells[0, stg_Tournaments.Row]);
  end;
end;

procedure TFrmMain.SpeedButton3Click(Sender: TObject);
begin
  uFrmEdittables.ShowForm(true, true, stg_Tables.Cells[0, stg_Tables.Row]);
end;

procedure TFrmMain.SpeedButton40Click(Sender: TObject);
begin
  uFrmEditTournamentRounds.ShowForm(false, false, stg_RoundTypeRounds.Cells[0, stg_RoundTypeRounds.Row], true);
end;

procedure TFrmMain.SpeedButton41Click(Sender: TObject);
begin
  uFrmEditTournamentRounds.ShowForm(true, false, stg_RoundTypeRounds.Cells[0, stg_RoundTypeRounds.Row], true);
end;

procedure TFrmMain.SpeedButton42Click(Sender: TObject);
begin
  if MessageDlg(_('Delete last sequence?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('TOURNAMENT_ROUND_TYPE_DETAILS', 'ID=(SELECT MAX(ID) FROM TOURNAMENT_ROUND_TYPE_DETAILS WHERE ROUND_TYPE_ID=' + stg_RoundTypes.Cells[0, stg_RoundTypes.Row] + ')');
    GetGridData(stg_RoundTypeRounds, SQL_RoundTypeDetails + stg_RoundTypes.Cells[0, stg_RoundTypes.Row] + ' ORDER BY SEQ_INDEX ASC', false);
  end;
end;

procedure TFrmMain.SpeedButton43Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('COUNTRIES', 'ID=' + stg_Countries.Cells[0, stg_Countries.Row]);
    GetGridData(stg_Countries, SQL_Countries, false);
  end;
end;

procedure TFrmMain.SpeedButton44Click(Sender: TObject);
begin
  uFrmEditRoundTypes.ShowForm(false, false, stg_RoundTypes.Cells[0, stg_RoundTypes.Row]);
end;

procedure TFrmMain.SpeedButton45Click(Sender: TObject);
begin
  uFrmEditRoundTypes.ShowForm(true, false, stg_RoundTypes.Cells[0, stg_RoundTypes.Row]);
end;

procedure TFrmMain.SpeedButton46Click(Sender: TObject);
begin
  uFrmEditRoundTypes.ShowForm(true, true, stg_RoundTypes.Cells[0, stg_RoundTypes.Row]);
end;

procedure TFrmMain.SpeedButton47Click(Sender: TObject);
begin
  try
    if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      DeleteDataFromDB('TOURNAMENT_ROUND_TYPE_DETAILS', 'ROUND_TYPE_ID=' + stg_RoundTypes.Cells[0, stg_RoundTypes.Row]);
      DeleteDataFromDB('TOURNAMENT_ROUND_TYPES', 'ID=' + stg_RoundTypes.Cells[0, stg_RoundTypes.Row]);
      GetGridData(stg_RoundTypes, SQL_RoundTypes, true);
    end;
  except
    on E: Exception do
    begin
      ShowMessage(_(E.Message));
    end;
  end;
end;

procedure TFrmMain.SpeedButton48Click(Sender: TObject);
begin
  uFrmEditDrinks.ShowForm(true, false, stg_Drinks.Cells[0, stg_Drinks.Row]);
end;

procedure TFrmMain.SpeedButton49Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('DRINKS', 'ID=' + stg_Drinks.Cells[0, stg_Drinks.Row]);
    GetGridData(stg_Drinks, SQL_Drinks, false);
  end;
end;

procedure TFrmMain.SpeedButton4Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('TABLES', 'ID=' + stg_Tables.Cells[0, stg_Tables.Row]);
    GetGridData(stg_Tables, SQL_Tables, true);
  end;
end;

procedure TFrmMain.SpeedButton50Click(Sender: TObject);
begin
  uFrmEditTableZones.ShowForm(false, false, stg_TableZones.Cells[0, stg_TableZones.Row]);
end;

procedure TFrmMain.SpeedButton51Click(Sender: TObject);
begin
  uFrmEditTableZones.ShowForm(true, false, stg_TableZones.Cells[0, stg_TableZones.Row]);
end;

procedure TFrmMain.SpeedButton52Click(Sender: TObject);
begin
  uFrmEditTableZones.ShowForm(true, true, stg_TableZones.Cells[0, stg_TableZones.Row]);
end;

procedure TFrmMain.SpeedButton53Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('TABLE_ZONES', 'ID=' + stg_TableZones.Cells[0, stg_TableZones.Row]);
    GetGridData(stg_TableZones, SQL_TableZones, true);
  end;
end;

procedure TFrmMain.SpeedButton54Click(Sender: TObject);
begin
  uFrmEditTournamentTypes.ShowForm(false, false, stg_TournamentTypes.Cells[0, stg_TournamentTypes.Row]);
end;

procedure TFrmMain.SpeedButton55Click(Sender: TObject);
begin
  uFrmEditTournamentTypes.ShowForm(true, false, stg_TournamentTypes.Cells[0, stg_TournamentTypes.Row]);
end;

procedure TFrmMain.SpeedButton56Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('TOURNAMENT_TYPES', 'ID=' + stg_TournamentTypes.Cells[0, stg_TournamentTypes.Row]);
    GetGridData(stg_TournamentTypes, SQL_TournamentTypes, true);
  end;
end;

procedure TFrmMain.SpeedButton57Click(Sender: TObject);
begin
  uFrmEditCasinoInventory.ShowForm(false, false, stg_CasinoInventory.Cells[0, stg_CasinoInventory.Row]);
end;

procedure TFrmMain.SpeedButton58Click(Sender: TObject);
begin
  uFrmEditCasinoInventory.ShowForm(true, false, stg_CasinoInventory.Cells[0, stg_CasinoInventory.Row]);
end;

procedure TFrmMain.SpeedButton59Click(Sender: TObject);
begin
  uFrmEditCasinoInventory.ShowForm(true, true, stg_CasinoInventory.Cells[0, stg_CasinoInventory.Row]);
end;

procedure TFrmMain.SpeedButton5Click(Sender: TObject);
begin
  uFrmEditTournaments.ShowForm(false, false, stg_Tournaments.Cells[0, stg_Tournaments.Row]);
end;

procedure TFrmMain.SpeedButton60Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('CASINO_INVENTORY', 'ID=' + stg_CasinoInventory.Cells[0, stg_CasinoInventory.Row]);
    GetGridData(stg_CasinoInventory, SQL_CasinoInventory + stg_CasinoInventory.Cells[0, stg_CasinoInventory.Row], true);
  end;
end;

procedure TFrmMain.SpeedButton61Click(Sender: TObject);
begin
  uFrmEditRakeValues.ShowForm(false, false, stg_RakeValues.Cells[0, stg_RakeValues.Row]);
end;

procedure TFrmMain.SpeedButton62Click(Sender: TObject);
begin
  uFrmEditRakeValues.ShowForm(true, false, stg_RakeValues.Cells[0, stg_RakeValues.Row]);
end;

procedure TFrmMain.SpeedButton63Click(Sender: TObject);
begin
  uFrmEditRakeValues.ShowForm(true, true, stg_RakeValues.Cells[0, stg_RakeValues.Row]);
end;

procedure TFrmMain.SpeedButton64Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('RAKE_VALUES', 'ID=' + stg_RakeValues.Cells[0, stg_RakeValues.Row]);
    GetGridData(stg_RakeValues, SQL_RakeValues + stg_RakeValues.Cells[0, stg_RakeValues.Row], true);
  end;
end;

procedure TFrmMain.SpeedButton65Click(Sender: TObject);
begin
  uFrmEditRakes.ShowForm(false, false, stg_Rakes.Cells[0, stg_Rakes.Row]);
end;

procedure TFrmMain.SpeedButton66Click(Sender: TObject);
begin
  uFrmEditRakes.ShowForm(true, false, stg_Rakes.Cells[0, stg_Rakes.Row]);
end;

procedure TFrmMain.SpeedButton67Click(Sender: TObject);
begin
  uFrmEditRakes.ShowForm(true, true, stg_Rakes.Cells[0, stg_Rakes.Row]);
end;

procedure TFrmMain.SpeedButton68Click(Sender: TObject);
begin
  try
    if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      DeleteDataFromDB('RAKES', 'ID=' + stg_Rakes.Cells[0, stg_Rakes.Row]);
      GetGridData(stg_Rakes, SQL_Rakes, true);
    end;
  except
    on E: Exception do
    begin

    end;
  end;
end;

procedure TFrmMain.SpeedButton69Click(Sender: TObject);
begin
  if stg_Profiles.Cells[0, stg_Profiles.Row] <> '' then
  begin
    frm_SelectObjects.ShowSelectObjectsForm(stg_LoginForms, true, 'LOGIN_FORM_PROFILES',
      'SELECT * FROM LOGIN_FORMS WHERE ID NOT IN (SELECT LF.ID FROM LOGIN_FORM_PROFILES LFP' + ' JOIN LOGIN_FORMS LF ON LFP.LOGIN_FORM_ID=LF.ID WHERE PROFILE_ID=' + stg_Profiles.Cells
        [0, stg_Profiles.Row] + ')',
      'SELECT LF.ID, LF.NAME, LFP.ID FROM LOGIN_FORM_PROFILES LFP JOIN LOGIN_FORMS LF ON LFP.LOGIN_FORM_ID=LF.ID WHERE PROFILE_ID=' + stg_Profiles.Cells[0, stg_Profiles.Row],
      stg_Profiles.Cells[0, stg_Profiles.Row]);
  end;
end;

procedure TFrmMain.SpeedButton6Click(Sender: TObject);
begin
  if stg_Tournaments.Cells[0, stg_Tournaments.Row] <> '' then
  begin
    uFrmEditTournaments.ShowForm(true, false, stg_Tournaments.Cells[0, stg_Tournaments.Row]);
  end;
end;

procedure TFrmMain.SpeedButton7Click(Sender: TObject);
begin
  m_OrigTournamentID := stg_Tournaments.Cells[0, stg_Tournaments.Row];
  uFrmEditTournaments.ShowForm(true, true, stg_Tournaments.Cells[0, stg_Tournaments.Row]);
end;

procedure TFrmMain.SpeedButton8Click(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    if CheckSoldTicketForTournament(stg_Tournaments.Cells[0, stg_Tournaments.Row]) then
    begin
      MessageDlg(_('Cannot be deleted. Tickets are sold for this tournament.'), mtInformation, [mbOK], 0);
    end
    else
    begin
      UpdateDataToDB('TOURNAMENTS', 'DELETED=1', 'ID=' + stg_Tournaments.Cells[0, stg_Tournaments.Row]);
      GetGridData(stg_Tournaments, SQL_Tournaments, false);
    end;
  end;
end;

function TFrmMain.CheckSoldTicketForTournament(TournamentID: string): Boolean;
begin
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('SELECT COUNT(0) AS COUNT FROM TOURNAMENTS T JOIN TICKETS TI ON T.ID=TI.TOURNAMENT_ID WHERE TI.DELETED=0 AND T.ID=' + TournamentID);
  OracleQuery1.Execute;
  result := OracleQuery1.Field('COUNT') <> '0';
end;

procedure TFrmMain.SpeedButton9Click(Sender: TObject);
begin
  uFrmEditTournamentRounds.ShowForm(false, false, stg_TournamentRounds.Cells[0, stg_TournamentRounds.Row]);
end;

procedure TFrmMain.HideAllDetailButtons(Sender: TObject);
var
  j: Integer;
begin
  // disable ALL ACTIONS
  if m_FrmHall <> nil then
  begin
    if m_FrmHall.m_FrmTableDetail <> nil then
    begin
      m_FrmHall.m_FrmTableDetail.tmr_ClockUpdate.Enabled := false;
    end;
  end;
  for j := 0 to pnl_MenuDetail.ControlCount - 1 do
  begin
    if (pnl_MenuDetail.Controls[j] is TSpeedButton) then
    begin
      pnl_MenuDetail.Controls[j].Visible := false; ;
    end
  end;
  if Sender is TSpeedButton then
  begin
    pnl_ActiveMenuButton.Visible := true;
    pnl_ActiveMenuButton.Top := TSpeedButton(Sender).Top;
    pnl_ActiveMenuButton.Left := TSpeedButton(Sender).Width - pnl_ActiveMenuButton.Width;
    pnl_ActiveMenuButton.height := TSpeedButton(Sender).height;
  end;
  SetActiveSubMenuButton(nil);
end;

procedure TFrmMain.SetActiveSubMenuButton(Sender: TObject);
begin
  pnl_ActiveSubMenuButton.Visible := false;
  if Sender is TSpeedButton then
  begin
    pnl_ActiveSubMenuButton.Visible := true;
    pnl_ActiveSubMenuButton.Top := TSpeedButton(Sender).Top;
    pnl_ActiveSubMenuButton.Left := TSpeedButton(Sender).Width - pnl_ActiveSubMenuButton.Width;
    pnl_ActiveSubMenuButton.height := TSpeedButton(Sender).height;
  end;
end;

procedure TFrmMain.btn_MenuDrinkOrdersClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  ShowTabSheet(tbs_Blank);
  btn_MenuDrinks.Visible := true;
  btn_DrinkOrders.Visible := true;
end;

procedure TFrmMain.btn_MenuEMailingClick(Sender: TObject);
begin
  ShowTabSheet(tbs_EMailing);
  FrmEMailing.Parent := tbs_EMailing;
  FrmEMailing.SetData();
end;

procedure TFrmMain.btn_MenuGeneralClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  act_General.Execute;
end;

procedure TFrmMain.btn_MenuPlayersClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  act_Players.Execute;
end;

procedure TFrmMain.btn_MenuPrepareTournamentClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  act_PrepareTournament.Execute;
end;

procedure TFrmMain.btn_MenuReportClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  ShowTabSheet(tbs_Blank);
  btn_UserAccess.Visible := true;
  btn_ReportTournament.Visible := true;
  btn_ReportDataTracking.Visible := true;
  btn_ReportCashGame.Visible := true;
  btn_PlayerPoints.Visible := true;
  btn_ReportDrinkOrders.Visible := true;
  btn_ReportEvents.Visible := true;
  btn_ReportDealerActivity.Visible := true;
end;

procedure TFrmMain.btn_MenuTicketsClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  act_Tickets.Execute;
end;

procedure TFrmMain.btn_MenuUsersClick(Sender: TObject);
begin
  HideAllDetailButtons(Sender);
  act_Users.Execute;
end;

procedure TFrmMain.btn_NewClick(Sender: TObject);
begin
  uFrmEditUsers.ShowForm(false, false, stg_Users.Cells[0, stg_Users.Row]);
end;

procedure TFrmMain.btn_OrderDrinkClick(Sender: TObject);
begin
  FrmOrderDrink.ShowOrderDrinkForm('', '', '');
  btn_DrinkOrders.Click();
end;

procedure TFrmMain.btn_PhotoFromWebCamClick(Sender: TObject);
begin
  ShowCAMphotoForm(stg_Users.Cells[0, stg_Users.Row]);
  if (FrmCameraGetImage.FrmSubjectImage.img_TakenPhoto.Picture <> nil) and (FrmCameraGetImage.ImageValid) then
    img_User.Picture := FrmCameraGetImage.FrmSubjectImage.img_TakenPhoto.Picture;
end;

procedure TFrmMain.btn_RakeValuesClick(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_RakeValues);
  ShowTabSheet(tbs_RakeValues);
  GetGridData(stg_Rakes, SQL_Rakes, true);
  stg_RakesSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.btn_ReportDealerActivityClick(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_ReportEvents);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := _('DEALER_ACTIVITY');
  lbl_ReportName.Hint := 'DEALER_ACTIVITY';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.btn_ReportDrinkOrdersClick(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_ReportTournament);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := _('DRINK ORDERS');
  lbl_ReportName.Hint := 'DRINK_ORDERS';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.btn_ReportEventsClick(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_ReportEvents);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := _('EVENTS');
  lbl_ReportName.Hint := 'EVENTS';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.btn_ReprintClick(Sender: TObject);
begin
  if stg_GridReport.Fields[2].Text = 'CAGE CLOSE' then
  begin
    FrmPrintCageClose.SetData(stg_GridReport.Fields[0].Text, OracleSession1);
  end
  else
  begin
    Printer.BeginDoc;
    with Printer do
      try
        stg_GridReport.PaintTo(Canvas, 200, 200);
      finally
        Printer.EndDoc;
      end;
  end;
end;

procedure TFrmMain.stg_CashGamesDblClick(Sender: TObject);
var
  Status, GameName: string;
  SelRow: Integer;
begin
  Status := stg_CashGames.Cells[1, stg_CashGames.Row];
  GameName := stg_CashGames.Cells[3, stg_CashGames.Row];
  SelRow := stg_CashGames.Row;
  if Status = 'CLOSED' then
  begin
    Status := 'OPEN';
  end
  else if Status = 'OPEN' then
  begin
    Status := 'CLOSED';
    // delete table
  end;
  if MessageDlg(_('Change cash game' + ' ' + GameName + ' ' + 'status to') + ' ' + Status + '?', mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    if Status = 'CLOSED' then
    begin
      OracleQuery1.SQL.Clear;
      OracleQuery1.SQL.Text := ('SELECT COUNT(0) AS PLAYERS_ON FROM CASH_GAMES CG' + ' JOIN CASH_GAME_TICKETS CGT ON CGT.CASH_GAME_ID=CG.ID' + ' WHERE CGT.OUT_DATETIME IS NULL AND CG.ID=' +
          stg_CashGames.Cells[0, stg_CashGames.Row]);
      OracleQuery1.Execute;
      if OracleQuery1.Field('PLAYERS_ON') = 0 then
      begin
        UpdateDataToDB('CASH_GAMES', 'TABLE_ID=NULL', 'ID=' + stg_CashGames.Cells[0, stg_CashGames.Row]);
        UpdateDataToDB('CASH_GAMES', 'STATUS=' + '''' + Status + '''', 'ID=' + stg_CashGames.Cells[0, stg_CashGames.Row]);
        UpdateDataToDB('CASH_GAME_OPENS', 'CLOSE=(SELECT SYSDATE FROM DUAL)',
          'ID=(SELECT ID FROM CASH_GAME_OPENS WHERE CLOSE IS NULL AND CASH_GAME_ID=' + stg_CashGames.Cells[0, stg_CashGames.Row] + ')');
      end
      else
      begin
        ShowMessage(_('Cash game have players on table!'));
      end;
    end
    else
    begin
      InsertDataIntoDB('CASH_GAME_OPENS', 'OPEN, CASH_GAME_ID, GAMING_DAY', '(SELECT SYSDATE FROM DUAL)' + ',' + stg_CashGames.Cells[0, stg_CashGames.Row] + ',' + '(SELECT * FROM GET_GD_START_TIME)');
      UpdateDataToDB('CASH_GAMES', 'STATUS=' + '''' + Status + '''', 'ID=' + stg_CashGames.Cells[0, stg_CashGames.Row]);
    end;
    FrmMain.GetGridData(FrmMain.stg_CashGames, SQL_CashGames, false);
    SelectGridRow(FrmMain.stg_CashGames, SelRow);
    FrmMain.stg_CashGamesSelectCell(self, 0, SelRow, CanSelect);
  end;
end;

procedure TFrmMain.stg_CashGamesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_CashGamesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  if ARow > 1 then
  begin
    FrmMain.GetGridData(stg_CashGameTables, 'SELECT TA.ID,TA.NAME FROM CASH_GAMES CG JOIN TABLES TA ON TA.ID=CG.TABLE_ID WHERE CG.ID=' + stg_CashGames.Cells[0, ARow], true);
    FrmMain.GetGridData(stg_Rake,
      'SELECT ID, FROM_VALUE, TO_VALUE,VALUE, CASE WHEN IS_PERCENT=1 THEN ''%'' ELSE ''CURRENCY'' END AS PERCENT FROM RAKE_VALUES WHERE RAKE_ID=(SELECT RAKE_ID FROM CASH_GAMES WHERE ID=' +
        stg_CashGames.Cells[0, ARow] + ')', true);
  end
  else
  begin
    ClearStringGrid(stg_CashGameTables);
    ClearStringGrid(stg_Rake);
  end;
  img_AlertCashTables.Visible := false;
  tmr_Alert.Enabled := true;
end;

procedure TFrmMain.stg_CashGameTablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_CasinoInventoryClick(Sender: TObject);
begin
  stg_CasinoInventory.Refresh;
end;

procedure TFrmMain.stg_CasinoInventoryDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_CasinoInventorySelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  stg_CasinoInventory.Refresh;
end;

procedure TFrmMain.stg_CountriesClick(Sender: TObject);
begin
  stg_Countries.Refresh;
end;

procedure TFrmMain.stg_CountriesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_CountriesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  if stg_Countries.Cells[0, stg_Countries.Row] <> '' then
  begin
    img_Country.Picture := uUtils.GetImage('SELECT IMAGE, IMAGE_TYPE FROM COUNTRIES WHERE ID=' + stg_Countries.Cells[0, ARow], OracleSession1);
  end;
  stg_Countries.Refresh;
end;

procedure TFrmMain.stg_DrinkOrdersDblClick(Sender: TObject);
begin
  if MessageDlg(_('Release drink?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    UpdateDataToDB('DRINK_ORDERS', 'completed=1', 'ID=' + stg_DrinkOrders.Cells[0, stg_DrinkOrders.Row]);
    FrmPrintBarBill.SetData(stg_DrinkOrders.Cells[0, stg_DrinkOrders.Row], FrmMain.OracleSession1);
    btn_DrinkOrders.Click;
  end;
end;

procedure TFrmMain.stg_DrinkOrdersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_DrinksClick(Sender: TObject);
begin
  stg_Drinks.Refresh;
end;

procedure TFrmMain.stg_DrinksDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_DrinksSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  stg_Drinks.Refresh;
end;

procedure TFrmMain.stg_DrinkTypesClick(Sender: TObject);
begin
  stg_DrinkTypes.Refresh;
end;

procedure TFrmMain.stg_DrinkTypesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_DrinkTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  stg_DrinkTypes.Refresh;
end;

procedure TFrmMain.stg_GridReportCellClick(Column: TColumn);
var
  Query: string;
begin
  if lbl_ReportName.Hint = 'TOURNAMENTS' then
  begin
    if stg_GridReport.Fields[0].Text <> '' then
    begin
      Query := (SQL_ReportTournamentsTickets + stg_GridReport.Fields[0].Text);
      OracleDataSetReportDetail.Close;
      OracleDataSetReportDetail.SQL.Clear;
      OracleDataSetReportDetail.SQL.Text := (Query + OrderReportBy);
      OracleDataSetReportDetail.Open;
      // ----
      stg_ReportDetail.Columns[0].Width := 0;
      stg_ReportDetail.Columns[1].Width := 40;
      stg_ReportDetail.Columns[2].Width := 50;
      stg_ReportDetail.Columns[3].Width := 120;
      stg_ReportDetail.Columns[4].Width := 80;
      stg_ReportDetail.Columns[5].Width := 70;
      stg_ReportDetail.Columns[6].Width := 120;
      stg_ReportDetail.Columns[7].Width := 120;
    end;
  end
  else if lbl_ReportName.Hint = 'CASH_GAMES' then
  begin
    if stg_GridReport.Fields[0].Text <> '' then
    begin
      Query :=
        'SELECT CGT.id, (SELECT PL.NAME||'' ''||PL.SURNAME FROM PLAYERS PL WHERE PL.ID=PLAYER_ID) AS PLAYER, SEAT_NUM, INPUT_VALUE, OUTPUT_VALUE, (OUTPUT_VALUE-INPUT_VALUE) AS WIN, CGT.DATETIME,'
        + ' CGTR.VALUE, CASE WHEN CGTR.VALUE IS NULL AND CGTR.DATETIME IS NOT NULL THEN CGTR.ID END AS DO_REBUY_ID, PLAYER_ID' +
        ' FROM  CASH_GAME_TICKETS CGT LEFT JOIN (SELECT * FROM CASH_GAME_TICKET_REBUYS WHERE VALUE IS NULL AND ON_TABLE=1) CGTR ON CGT.ID=CGTR.CASH_GAME_TICKET_ID' +
        ' where TRUNC(CGT.gaming_day)=(''' + stg_GridReport.Fields[3].Text + ''')';
      OracleDataSetReportDetail.Close;
      OracleDataSetReportDetail.SQL.Clear;
      OracleDataSetReportDetail.SQL.Text := (Query + OrderReportBy);
      OracleDataSetReportDetail.Open;
      // ----
      stg_ReportDetail.Columns[0].Width := 0;
      stg_ReportDetail.Columns[1].Width := 140;
      stg_ReportDetail.Columns[2].Width := 40;
      stg_ReportDetail.Columns[3].Width := 70;
      stg_ReportDetail.Columns[4].Width := 70;
      stg_ReportDetail.Columns[5].Width := 70;
      stg_ReportDetail.Columns[6].Width := 130;
      stg_ReportDetail.Columns[7].Width := 70;
    end;
  end
end;

procedure TFrmMain.stg_GridReportDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_GridReportDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if (stg_GridReport.DataSource.DataSet.RecNo = stg_GridReport.DataSource.DataSet.RecordCount) then
  begin
    if (lbl_ReportName.Hint = 'TOURNAMENTS') or (lbl_ReportName.Hint = 'DRINK_ORDERS') then
    begin
      stg_GridReport.Canvas.Brush.Color := clGray;
      stg_GridReport.Canvas.Font.Style := stg_GridReport.Canvas.Font.Style + [fsBold];
      stg_GridReport.Canvas.Font.Color := clWhite;
      stg_GridReport.DefaultDrawColumnCell(Rect, DataCol, Column, State);
    end;
  end;
end;

procedure TFrmMain.stg_GridReportKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if ((Key = VK_DOWN)) and (pgc_Main.ActivePage = tbs_Reports) then
  begin
    stg_GridReportCellClick(nil);
  end;
  if ((Key = VK_UP)) and (pgc_Main.ActivePage = tbs_Reports) then
  begin
    stg_GridReportCellClick(nil);
  end;
end;

procedure TFrmMain.stg_GridReportMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  pt: TGridcoord;
begin
  pt := stg_GridReport.MouseCoord(X, Y);
  if pt.Y = 0 then
    stg_GridReport.Cursor := crHandPoint
  else
    stg_GridReport.Cursor := crDefault;
end;

procedure TFrmMain.stg_GridReportMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
  OracleDataSetReportDetail.Close;
  stg_GridReport.OnCellClick(nil);

end;

procedure TFrmMain.stg_GridReportMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
  OracleDataSetReportDetail.Close;
end;

procedure TFrmMain.stg_GridReportTitleClick(Column: TColumn);
begin
  // Restore the title settings, otherwise everything
  // will be blue after a while
  OrderReportBy := '';
  if ReportAscDesc = ' asc ' then
  begin
    ReportAscDesc := ' desc ';
  end
  else
  begin
    ReportAscDesc := ' asc '
  end;
  OrderReportBy := ' order by ' + inttostr(Column.Index + 1) + ReportAscDesc;
  stg_GridReport.Columns.RestoreDefaults;
  btn_GetReportData.Click();
  if ReportAscDesc = ' desc ' then
  begin
    Column.Title.Caption := '/\ ' + Column.Title.Caption;
  end
  else
  begin
    Column.Title.Caption := '\/ ' + Column.Title.Caption;
  end;
  Column.Title.Font.Color := clBlue;
end;

procedure TFrmMain.stg_PlayerFromBreakTableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_PrivilegesClick(Sender: TObject);
begin
  stg_Privileges.Refresh;
end;

procedure TFrmMain.stg_PrivilegesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_ProfilesClick(Sender: TObject);
begin
  stg_Profiles.Refresh;
end;

procedure TFrmMain.stg_ProfilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_ProfilesFilterClick(Sender: TObject);
begin
  stg_ProfilesFilter.Refresh;
end;

procedure TFrmMain.stg_ProfilesFilterDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_ProfilesFilterSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  ID: string;
begin
  ID := stg_ProfilesFilter.Cells[0, ARow];
  if (ID = '-1') or (ID = 'ID') then
  begin
    ID := '';
  end
  else
  begin
    ID := ' and profile_id=' + ID;
  end;
  GetGridData(stg_Users, SQL_Users + ID, true);
  stg_ProfilesFilter.Refresh;
end;

procedure TFrmMain.stg_ProfilesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  btn_EditProfiles.Enabled := false;
  if ARow > 0 then
  begin
    GetGridData(FrmMain.stg_Privileges, 'select php.id, pr.NAME from PROFILE_HAS_PRIVILEGE php join PRIVILEGE pr on pr.ID=php.PRIVILEGE_ID where php.PROFILE_ID = ' + stg_Profiles.Cells[0, ARow],
      true);
    GetGridData(FrmMain.stg_LoginForms, SQL_LoginFormsProfiles + stg_Profiles.Cells[0, ARow], true);
    btn_EditProfiles.Enabled := true;
  end;
  stg_Profiles.Refresh;
end;

procedure TFrmMain.stg_RakeDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_RakesClick(Sender: TObject);
begin
  stg_Rakes.Refresh;
end;

procedure TFrmMain.stg_RakesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_RakesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  if (stg_Rakes.Cells[0, ARow] <> '') and (ARow > 0) then
  begin
    WhereCond := ' WHERE RAKE_ID=' + stg_Rakes.Cells[0, ARow];
    GetGridData(stg_RakeValues, SQL_RakeValues + WhereCond + ' ORDER BY FROM_VALUE ASC', false);
    stg_RakeValues.ColWidths[0] := -1;
    stg_RakeValues.ColWidths[1] := -1;
    stg_RakeValues.ColWidths[2] := 90;
    stg_RakeValues.ColWidths[3] := 90;
    stg_RakeValues.ColWidths[4] := 90;
    stg_RakeValues.ColWidths[5] := 90;
    stg_RakeValuesSelectCell(self, 0, 1, CanSelect);
  end;
end;

procedure TFrmMain.stg_ReportDetailTitleClick(Column: TColumn);
begin
  OrderReportBy := '';
  if ReportAscDesc = ' asc ' then
  begin
    ReportAscDesc := ' desc ';
  end
  else
  begin
    ReportAscDesc := ' asc '
  end;
  OrderReportBy := ' order by ' + inttostr(Column.Index + 1) + ReportAscDesc;
  stg_ReportDetail.Columns.RestoreDefaults;
  stg_GridReportCellClick(Column);
  if ReportAscDesc = ' desc ' then
  begin
    Column.Title.Caption := '/\ ' + Column.Title.Caption;
  end
  else
  begin
    Column.Title.Caption := '\/ ' + Column.Title.Caption;
  end;
  Column.Title.Font.Color := clBlue;
end;

procedure TFrmMain.stg_RoundTypesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_RoundTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  SpeedButton40.Enabled := false;
  SpeedButton41.Enabled := false;
  SpeedButton42.Enabled := false;
  WhereCond := stg_RoundTypes.Cells[0, ARow];
  if (ARow > 1) then
  begin
    if WhereCond = '' then
    begin
      WhereCond := '-1';
    end
    else
    begin
      SpeedButton40.Enabled := true;
      SpeedButton41.Enabled := true;
      SpeedButton42.Enabled := true;
    end;
    PrevTournamentRow := ARow;
    GetGridData(stg_RoundTypeRounds, SQL_RoundTypeDetails + WhereCond + ' ORDER BY SEQ_INDEX ASC', false);
    stg_RoundTypeRounds.ColWidths[1] := 60;
    stg_RoundTypeRounds.ColWidths[2] := 60;
    stg_RoundTypeRounds.ColWidths[3] := 60;
    stg_RoundTypeRounds.ColWidths[4] := 60;
    stg_RoundTypeRounds.ColWidths[5] := 60;
  end;
end;

procedure TFrmMain.ClientSocket1Disconnect(Sender: TObject; Socket: TCustomWinSocket);
begin
  ClientSocket1.Close;
end;

procedure TFrmMain.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
  ErrorCode := 0;
  // this line solve your problems about asyncroneus socket error
end;

procedure TFrmMain.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
var
  EventType, TournamentID, TableID: string;
begin
  uUtils.SocketTextParse(Socket.ReceiveText, EventType, TournamentID, TableID);
  if (EventType = EventTypeFromTable) or (EventType = EventTypeTicket) then
  begin
    if (frmCageTournament <> nil) and (pgc_Main.ActivePage = tbs_CageTournament) then
    begin
      frmCageTournament.dtp_DateChange(self);
    end;
    if m_FrmHall <> nil then
    begin
      if (m_FrmHall.m_FrmTableDetail <> nil) and (pgc_Main.ActivePage = tbs_Hall) then
      begin
        if (m_FrmHall.pgc_Hall.ActivePage = m_FrmHall.tbs_Table) then
        begin
          m_FrmHall.m_FrmTableDetail.FrmTable.RefreshTableView();
        end;
      end
      else if (m_FrmHall.m_FrmTableDetail <> nil) and (pgc_Main.ActivePage = tbs_Hall) then
      begin
        if (m_FrmHall.pgc_Hall.ActivePage = m_FrmHall.tbs_Hall) then
        begin
          btn_MenuHallView.Click;
        end;
      end;
    end;
  end
  else if (EventType = EventTypeCashierChange) and (pgc_Main.ActivePage = tbs_CageTournament) then
  begin
    if (frmCageTournament <> nil) then
    begin
      frmCageTournament.GetLoggedCahiers();
    end;
  end
  else if (EventType = EventTypeCashierChange) and (pgc_Main.ActivePage = tbs_DrinkOrders) then
  begin
    GetLoggedBarman();
  end;
end;

procedure TFrmMain.CloneTournamentRounds(FromTournamentID, ToTournamentID: string; FromRoundTypes, ToRoundTypes: Boolean);
var
  Query, SmallB, BigB, Ante, RebuyOrAddon: string;
  OracleQuery: TOracleQuery;
  TableNmFrom, WhereFieldNmFrom, TableNmTo, WhereFieldNmTo: string;
begin
  if FromRoundTypes and ToRoundTypes then
  begin
    TableNmFrom := 'TOURNAMENT_ROUND_TYPE_DETAILS';
    WhereFieldNmFrom := 'ROUND_TYPE_ID';
    TableNmTo := 'TOURNAMENT_ROUND_TYPE_DETAILS';
    WhereFieldNmTo := 'ROUND_TYPE_ID';
  end
  else if FromRoundTypes and not ToRoundTypes then
  begin
    TableNmFrom := 'TOURNAMENT_ROUND_TYPE_DETAILS';
    WhereFieldNmFrom := 'ROUND_TYPE_ID';
    TableNmTo := 'TOURNAMENT_ROUNDS';
    WhereFieldNmTo := 'TOURNAMENT_ID'
  end
  else if not FromRoundTypes and not ToRoundTypes then
  begin
    TableNmFrom := 'TOURNAMENT_ROUNDS';
    WhereFieldNmFrom := 'TOURNAMENT_ID';
    TableNmTo := 'TOURNAMENT_ROUNDS';
    WhereFieldNmTo := 'TOURNAMENT_ID'
  end;
  // check if new tournament have rounds
  Query := 'SELECT DURATION, IS_BREAK, ' + WhereFieldNmTo + ', SEQ_INDEX, SMALL_BLIND, BIG_BLIND, ANTE, REBUY_OR_ADDON FROM ' + TableNmTo + ' WHERE ' + WhereFieldNmTo + '=' + ToTournamentID;
  OracleQuery := TOracleQuery.Create(self);
  OracleQuery.Session := OracleSession1;
  OracleQuery.SQL.Clear;
  OracleQuery.SQL.Text := (Query);
  OracleQuery.Execute;
  if not OracleQuery.Eof then
  begin
    if MessageDlg(_('Selected tournament already have rounds! DO YOU WANT TO DELETE ROUNDS?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      Query := 'DELETE FROM ' + TableNmTo + ' WHERE ' + WhereFieldNmTo + '=' + ToTournamentID;
      OracleQuery := TOracleQuery.Create(self);
      OracleQuery.Session := OracleSession1;
      OracleQuery.SQL.Clear;
      OracleQuery.SQL.Text := (Query);
      OracleQuery.Execute;
    end
    else
    begin
      FreeAndNil(OracleQuery);
      exit;
    end;
    FreeAndNil(OracleQuery);
  end;
  // get data of original
  Query := 'SELECT DURATION, IS_BREAK, ' + WhereFieldNmFrom + ', SEQ_INDEX, SMALL_BLIND, BIG_BLIND, ANTE, REBUY_OR_ADDON FROM ' + TableNmFrom + ' WHERE ' + WhereFieldNmFrom + '=' + FromTournamentID;
  OracleQuery := TOracleQuery.Create(self);
  OracleQuery.Session := OracleSession1;
  OracleQuery.SQL.Clear;
  OracleQuery.SQL.Text := (Query);
  OracleQuery.Execute;
  while not OracleQuery.Eof do
  begin
    BigB := (OracleQuery.Field('BIG_BLIND'));
    SmallB := (OracleQuery.Field('SMALL_BLIND'));
    if BigB = '0' then
      BigB := '''' + '''';
    if SmallB = '0' then
      SmallB := '''' + '''';
    Ante := '''' + inttostr(OracleQuery.Field('ANTE')) + '''';
    RebuyOrAddon := '''' + OracleQuery.Field('REBUY_OR_ADDON') + '''';
    InsertDataIntoDB(TableNmTo, 'DURATION,IS_BREAK,' + WhereFieldNmTo + ',SEQ_INDEX,SMALL_BLIND,BIG_BLIND, ANTE, REBUY_OR_ADDON', inttostr(OracleQuery.Field('DURATION')) + ',' +
        (OracleQuery.Field('IS_BREAK')) + ',' + ToTournamentID + ',' + inttostr(OracleQuery.Field('SEQ_INDEX'))
        + ',' + '''' + SmallB + '''' + ',' + '''' + BigB + '''' + ',' + Ante + ',' + RebuyOrAddon);
    OracleQuery.Next;
  end;
  CopyRoundToTournament := false;
  FreeAndNil(OracleQuery);
end;

procedure TFrmMain.stg_TableForBreakingDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_TablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_TournamentRoundsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
  img_AlertRounds.Visible := false;
end;

procedure TFrmMain.stg_TournamentRoundsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  SpeedButton10.Enabled := false;
  SpeedButton12.Enabled := false;
  if (ARow > 1) and (stg_TournamentRounds.Cells[0, ARow] <> '') then
  begin
    SpeedButton10.Enabled := true;
    SpeedButton12.Enabled := true;
  end;
end;

procedure TFrmMain.stg_TournamentsDblClick(Sender: TObject);
begin
  SpeedButton6.Click;
end;

procedure TFrmMain.stg_TournamentsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_TournamentsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  SearchStringGrid(stg_Tournaments, GetCharFromVirtualKey(Key));
end;

procedure TFrmMain.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
  Value, S: string;
  drawrect: TRect;
  ColorGridBack: TColor;
  PlayerPosition, WinToPlayer: string;
begin
  ColorGridBack := $00E0E0E0;
  TStringGrid(Sender).FixedColor := clGray;
  TStringGrid(Sender).Canvas.Font.Size := 10;
  TStringGrid(Sender).Canvas.Font.Color := clBlack;
  // multiline fixed row
  if TStringGrid(Sender).FixedRows > 0 then
  begin
    if ARow = 1 then
    begin
      S := (Sender as TStringGrid).Cells[ACol, ARow];
      TStringGrid(Sender).Canvas.Brush.Color := TStringGrid(Sender).FixedColor;
      TStringGrid(Sender).Canvas.Font.Color := clWhite;
      If Length(S) > 0 then
      begin
        drawrect := Rect;
        TStringGrid(Sender).Canvas.fillrect(drawrect);
        DrawText((Sender as TStringGrid).Canvas.handle, Pchar(S), Length(S), drawrect, dt_calcrect or dt_wordbreak or DT_CENTER);
        If (drawrect.Bottom - drawrect.Top) > (Sender as TStringGrid).RowHeights[ARow] then (Sender as TStringGrid)
          .RowHeights[ARow] := (drawrect.Bottom - drawrect.Top)
          // changing the row height fires the event again!
        else
        begin
          drawrect.Right := Rect.Right;
          TStringGrid(Sender).Canvas.fillrect(drawrect);
          // DrawText((Sender as TStringGrid).canvas.handle, Pchar(S), Length(S), drawrect, dt_wordbreak or DT_CENTER);
        end;
      end;
    end;
  end;
  // END multiline fixed row
  if (ARow > 1) or (TStringGrid(Sender).FixedRows = 0) then
  begin
    // END Coloring tournament rows with today dates different
    S := TStringGrid(Sender).Cells[ACol, ARow];
    if (State = [gdSelected]) then
    begin
      TStringGrid(Sender).Canvas.Brush.Color := clSkyBlue;
      TStringGrid(Sender).Canvas.fillrect(Rect);
      // DrawText((Sender as TStringGrid).canvas.handle, Pchar(S), Length(S), Rect, dt_wordbreak or DT_CENTER);
    end
    else
    begin
      TStringGrid(Sender).Canvas.Brush.Color := ColorGridBack;
      TStringGrid(Sender).Canvas.fillrect(Rect);
      // DrawText((Sender as TStringGrid).canvas.handle, Pchar(S), Length(S), Rect, dt_wordbreak or DT_CENTER);
    end;
    // ---------------------------------------
    // Coloring cage tournament players grid
    if frmCageCashGame <> nil then
    begin
      if (Sender = frmCageCashGame.stg_Players) then
      begin
        if frmCageCashGame.stg_Players.Cells[6, ARow] <> '' then
        begin
          if (State <> [gdSelected]) then
          begin
            frmCageCashGame.stg_Players.Canvas.Brush.Color := frmCageCashGame.lbl_OutColor.Color;
            frmCageCashGame.stg_Players.Canvas.fillrect(Rect);
          end
          else
          begin
            frmCageCashGame.stg_Players.Canvas.Brush.Color := frmCageCashGame.lbl_OutColor.Color - $00252525;
            frmCageCashGame.stg_Players.Canvas.fillrect(Rect);
          end;
        end;
        if (frmCageCashGame.stg_Players.Cells[8, ARow] <> '') and (frmCageCashGame.stg_Players.Cells[10, ARow] = '') then
        begin
          if (State <> [gdSelected]) then
          begin
            frmCageCashGame.stg_Players.Canvas.Brush.Color := frmCageCashGame.lbl_RebColor.Color;
            frmCageCashGame.stg_Players.Canvas.fillrect(Rect);
          end
          else
          begin
            frmCageCashGame.stg_Players.Canvas.Brush.Color := frmCageCashGame.lbl_RebColor.Color - $00252525;
            frmCageCashGame.stg_Players.Canvas.fillrect(Rect);
          end;
        end;
      end;
    end;
    // ---------------------------------------
    // Coloring cage tournament players grid
    if frmCageTournament <> nil then
    begin
      if (Sender = frmCageTournament.stg_Players) then
      begin
        // player out datetime
        if (frmCageTournament.stg_Players.Cells[9, ARow] <> '') and (frmCageTournament.stg_Players.Cells[11, ARow] = '') then
        begin
          PlayerPosition := frmCageTournament.stg_Players.Cells[10, ARow];
          if PlayerPosition = '' then
            PlayerPosition := '0';
          if frmCageTournament.stg_Tournaments.Row > 1 then
          begin
            WinToPlayer := frmCageTournament.stg_Tournaments.Cells[16, frmCageTournament.stg_Tournaments.Row];
            if WinToPlayer = '' then
              WinToPlayer := '0';
            if (strToInt(WinToPlayer) >= strToInt(PlayerPosition)) then
            begin
              // players for payment
              if (State <> [gdSelected]) then
              begin
                frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_ToPayColor.Color;
                frmCageTournament.stg_Players.Canvas.fillrect(Rect);
              end
              else
              begin
                frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_ToPayColor.Color - $00252525;
                frmCageTournament.stg_Players.Canvas.fillrect(Rect);
              end;
            end
            else
            begin
              // players out wo payment
              if (State <> [gdSelected]) then
              begin
                frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_OutColor.Color;
                frmCageTournament.stg_Players.Canvas.fillrect(Rect);
              end
              else
              begin
                frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_OutColor.Color - $00252525;
                frmCageTournament.stg_Players.Canvas.fillrect(Rect);
              end;
            end;
          end;
        end
        else
        // player win value paid
          if (frmCageTournament.stg_Players.Cells[11, ARow] <> '') then
        begin
          if (State <> [gdSelected]) then
          begin
            frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_PaidColor.Color;
            frmCageTournament.stg_Players.Canvas.fillrect(Rect);
          end
          else
          begin
            frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_PaidColor.Color - $00252525;
            frmCageTournament.stg_Players.Canvas.fillrect(Rect);
          end;
        end
        else
        // player rebuy or addon from table must finish on cage
          if (frmCageTournament.stg_Players.Cells[13, ARow] <> '') or (frmCageTournament.stg_Players.Cells[14, ARow] <> '') then
        begin
          if (State <> [gdSelected]) then
          begin
            frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_AddRebColor.Color;
            frmCageTournament.stg_Players.Canvas.fillrect(Rect);
          end
          else
          begin
            frmCageTournament.stg_Players.Canvas.Brush.Color := frmCageTournament.lbl_AddRebColor.Color - $00252525;
            frmCageTournament.stg_Players.Canvas.fillrect(Rect);
          end;
        end;
      end;
      // ----------------------------------------------------
      // Coloring tournament rows with today dates different
      if (Sender = stg_Tournaments) or (Sender = frmCageTournament.stg_Tournaments) then
      begin
        if Sender = stg_Tournaments then
        begin
          Value := TStringGrid(Sender).Cells[1, ARow]
        end
        else
        begin
          Value := TStringGrid(Sender).Cells[4, ARow]
        end;
        Value := LeftStr(Value, 6);
        if pos(FormatDateTime('dd.mm.', now), Value) > 0 then
        begin
          if (State <> [gdSelected]) then
          begin
            if TStringGrid(Sender).Cells[13, ARow] = 'FINISHED' then
            begin
              TStringGrid(Sender).Canvas.Brush.Color := $0080FFFF;
            end
            else if (TStringGrid(Sender).Cells[13, ARow] = 'RUNNING') or (TStringGrid(Sender).Cells[13, ARow] = 'SEATING') then
            begin
              TStringGrid(Sender).Canvas.Brush.Color := $007DA5FF;
            end
            else
            begin
              if (Sender = stg_Tournaments) then
              begin
                TStringGrid(Sender).Canvas.Brush.Color := $00B3E0E1;
              end
              else
              begin
                TStringGrid(Sender).Canvas.Brush.Color := FrmMain.GridGreenColor;
              end;
            end;
          end
          else
          begin
            if TStringGrid(Sender).Cells[13, ARow] = 'FINISHED' then
            begin
              TStringGrid(Sender).Canvas.Brush.Color := $0000DFDF;
            end
            else if (TStringGrid(Sender).Cells[13, ARow] = 'RUNNING') or (TStringGrid(Sender).Cells[13, ARow] = 'SEATING') then
            begin
              TStringGrid(Sender).Canvas.Brush.Color := $000045FF;
            end
            else
            begin
              if (Sender = stg_Tournaments) then
              begin
                TStringGrid(Sender).Canvas.Brush.Color := $0081CBCD;
              end
              else
              begin
                TStringGrid(Sender).Canvas.Brush.Color := FrmMain.GridSelGreenColor;
              end;
            end;
          end;
          TStringGrid(Sender).Canvas.fillrect(Rect);
          // DrawText((Sender as TStringGrid).canvas.handle, Pchar(S), Length(S), Rect, dt_wordbreak or DT_CENTER);
        end;
      end;
    end;
  end;
  DrawText((Sender as TStringGrid).Canvas.handle, Pchar(S), Length(S), Rect, dt_wordbreak or DT_CENTER);
end;

procedure TFrmMain.stg_TournamentsSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  SearchGridStr := '';
  img_AlertTables.Visible := false;
  tmr_Alert.Enabled := true;
  SpeedButton6.Enabled := false;
  SpeedButton7.Enabled := false;
  SpeedButton8.Enabled := false;
  SpeedButton9.Enabled := false;
  btn_EditTourTables.Enabled := false;
  WhereCond := stg_Tournaments.Cells[0, ARow];
  if (ARow > 1) then
  begin
    if WhereCond = '' then
    begin
      WhereCond := '-1';
    end
    else
    begin
      SpeedButton6.Enabled := true;
      SpeedButton7.Enabled := true;
      SpeedButton8.Enabled := true;
      SpeedButton9.Enabled := true;
      btn_EditTourTables.Enabled := true;
    end;
    GetGridData(stg_TournamentTables, SQL_TournamentTables + WhereCond + ' Order by name', false);
    GetGridData(stg_TournamentRounds, SQL_TournamentRounds + WhereCond + ' ORDER BY SEQ_INDEX ASC', false);
    stg_TournamentTables.ColWidths[1] := stg_TournamentTables.Width;
    stg_TournamentRounds.ColWidths[1] := 70;
    stg_TournamentRounds.ColWidths[2] := 70;
    stg_TournamentRounds.ColWidths[3] := 70;
    stg_TournamentRounds.ColWidths[4] := 90;
    stg_TournamentRounds.ColWidths[5] := 80;
    stg_TournamentRounds.ColWidths[6] := 80;
    stg_TournamentRounds.ColWidths[7] := 100;
  end
  else
  begin
    ClearStringGrid(stg_TournamentTables);
    ClearStringGrid(stg_TournamentRounds);
  end;
end;

procedure TFrmMain.stg_TournamentTablesClick(Sender: TObject);
begin
  stg_TournamentTables.Refresh;
end;

procedure TFrmMain.stg_TournamentTablesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_TournamentTypesClick(Sender: TObject);
begin
  stg_TournamentTypes.Refresh;
end;

procedure TFrmMain.stg_TournamentTypesSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
  stg_TournamentTypes.Refresh;
end;

procedure TFrmMain.stg_UserProfilesDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_UsersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_UsersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  btn_EditProfiles.Enabled := false;
  btn_ChangePassword.Enabled := false;
  if ARow > 1 then
  begin
    WhereCond := stg_Users.Cells[0, ARow];
    if WhereCond = '' then
    begin
      WhereCond := '-1';
    end
    else
    begin
      btn_EditProfiles.Enabled := true;
      btn_ChangePassword.Enabled := true;
    end;
    GetGridData(FrmMain.stg_UserProfiles, 'select uhp.id, up.NAME from USER_HAS_PROFILE uhp join PROFILES up on up.ID=uhp.PROFILE_ID where uhp.USER_ID=' + WhereCond, true);
    FrmMain.img_User.Picture := uUtils.GetImage(SQL_User_Picture + WhereCond, FrmMain.OracleSession1);
  end;
end;

procedure TFrmMain.stg_WinDistributionDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_WinDistributionSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  SpeedButton25.Enabled := false;
  SpeedButton26.Enabled := false;
  SpeedButton27.Enabled := false;
  SpeedButton28.Enabled := false;
  SpeedButton14.Enabled := false;
  SpeedButton15.Enabled := false;
  SpeedButton16.Enabled := false;
  if ARow > 1 then
  begin
    WhereCond := stg_WinDistribution.Cells[0, ARow];
    if WhereCond = '' then
    begin
      WhereCond := '-1';
    end
    else
    begin
      SpeedButton25.Enabled := true;
      SpeedButton26.Enabled := true;
      SpeedButton27.Enabled := true;
      SpeedButton28.Enabled := true;
      SpeedButton14.Enabled := true;
      SpeedButton15.Enabled := true;
      SpeedButton16.Enabled := true;
    end;
    GetGridData(stg_WinNumPlayers, SQL_WinPlayersNum + WhereCond, true);
    stg_WinNumPlayersSelectCell(stg_WinNumPlayers, 0, 2, CanSelect);
  end;
end;

procedure TFrmMain.stg_WinNumPlayersDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_WinNumPlayersSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  SpeedButton21.Enabled := false;
  SpeedButton22.Enabled := false;
  SpeedButton23.Enabled := false;
  SpeedButton24.Enabled := false;
  SpeedButton26.Enabled := false;
  SpeedButton27.Enabled := false;
  SpeedButton28.Enabled := false;
  if ARow > 1 then
  begin
    WhereCond := stg_WinNumPlayers.Cells[0, ARow];
    if WhereCond = '' then
    begin
      WhereCond := '-1';
    end
    else
    begin
      SpeedButton21.Enabled := true;
      SpeedButton22.Enabled := true;
      SpeedButton23.Enabled := true;
      SpeedButton24.Enabled := true;
      SpeedButton26.Enabled := true;
      SpeedButton27.Enabled := true;
      SpeedButton28.Enabled := true;
      stg_WinPercentageSelectCell(self, 0, 2, CanSelect);
    end;
    GetGridData(stg_WinPercentage, SQL_WinPerc + WhereCond + ' ORDER BY SEQ_INDEX ASC', true);
    SumWinPercentage();
  end;
end;

procedure TFrmMain.tbs_CageTournamentHide(Sender: TObject);
begin
  frmCageTournament.m_FrmDisplay.TimerChangeScreen.Enabled := false;
  frmCageTournament.tmr_RefreshTime.Enabled := false;
end;

procedure TFrmMain.tbs_CageTournamentShow(Sender: TObject);
begin
  frmCageTournament.m_FrmDisplay.TimerChangeScreen.Enabled := true;
  frmCageTournament.tmr_RefreshTime.Enabled := true;
end;

procedure TFrmMain.tbs_LoginShow(Sender: TObject);
begin
  pnl_Login.Left := tbs_Login.Width div 2 - pnl_Login.Width div 2;
  pnl_Login.Top := tbs_Login.height div 2 - pnl_Login.height div 2;
  edt_Username.SetFocus;
end;

procedure TFrmMain.tbs_ReportsResize(Sender: TObject);
begin
  pnl_ReportDetail.height := Trunc(tbs_Reports.height * 0.4);
end;

procedure TFrmMain.tmr_AlertTimer(Sender: TObject);
begin
  tmr_Alert.Enabled := false;
  if pgc_Main.ActivePage = tbs_Tournaments then
  begin
    if stg_TournamentRounds.Cells[0, 2] = '' then
    begin
      img_AlertRounds.Visible := not img_AlertRounds.Visible;
      tmr_Alert.Enabled := true;
    end;
    if stg_TournamentTables.Cells[0, 2] = '' then
    begin
      img_AlertTables.Visible := not img_AlertTables.Visible;
      tmr_Alert.Enabled := true;
    end;
  end;
  if pgc_Main.ActivePage = tbs_CashGames then
  begin
    if stg_CashGameTables.Cells[0, 2] = '' then
    begin
      img_AlertCashTables.Visible := not img_AlertCashTables.Visible;
      tmr_Alert.Enabled := true;
    end;
  end;
end;

procedure TFrmMain.tmr_RefreshHallTimer(Sender: TObject);
begin
  btn_MenuHallView.Click;
end;

procedure TFrmMain.stg_WinPercentageDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
  GridDrawCell(Sender, ACol, ARow, Rect, State);
end;

procedure TFrmMain.stg_WinPercentageSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
  WhereCond: string;
begin
  SpeedButton22.Enabled := false;
  SpeedButton23.Enabled := false;
  SpeedButton24.Enabled := false;
  if ARow > 1 then
  begin
    WhereCond := stg_WinPercentage.Cells[0, ARow];
    if WhereCond <> '' then
    begin
      SpeedButton22.Enabled := true;
      SpeedButton23.Enabled := true;
      SpeedButton24.Enabled := true;
    end;
  end;
end;

procedure TFrmMain.edt_CashGameTablesClick(Sender: TObject);
var
  WhereCond: string;
begin
  if stg_CashGames.Cells[0, stg_CashGames.Row] <> '' then
  begin
    WhereCond := stg_CashGames.Cells[0, stg_CashGames.Row];
    frm_SelectObjects.ShowSelectObjectsForm(stg_CashGameTables, true, 'CASH_GAMES', 'SELECT DISTINCT(TA.ID), NAME FROM TABLES TA LEFT JOIN TOURNAMENT_TABLES TT ON TA.ID=TT.TABLE_ID' +
        ' WHERE (TA.ID NOT IN (SELECT TABLE_ID FROM TOURNAMENT_TABLES TT WHERE TOURNAMENT_ID IN (' + ' SELECT ID FROM GETTOURNAMENT_START_END_TIME' +
        ' WHERE STATUS<>''FINISHED'' AND (SELECT SYSDATE FROM DUAL) BETWEEN EVENT_START AND EVENT_END)' +
        ' ))AND (TA.ID NOT IN (SELECT DISTINCT(TABLE_ID) FROM CASH_GAMES WHERE TABLE_ID IS NOT NULL)) AND TA.CASH_GAME=1 ORDER BY NAME ASC',
      'SELECT TA.ID,TA.NAME, CG.ID FROM CASH_GAMES CG JOIN TABLES TA ON TA.ID=CG.TABLE_ID WHERE CG.ID=' + stg_CashGames.Cells[0, stg_CashGames.Row] + ' ORDER BY NAME',
      stg_CashGames.Cells[0, stg_CashGames.Row]);
    stg_CashGamesSelectCell(self, 0, stg_CashGames.Row, CanSelect);
  end;
end;

procedure TFrmMain.edt_PasswordKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
    btn_LoginOK.Click;
end;

procedure TFrmMain.edt_UsernameKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then
    btn_LoginOK.Click;
end;

procedure TFrmMain.HideAllTabs;
var
  i: Integer;
begin
  for i := 0 to pgc_Main.PageCount - 1 do
  begin
    pgc_Main.Pages[i].TabVisible := false;
  end;
end;

procedure TFrmMain.img_BarmanClick(Sender: TObject);
var
  UserID: string;
begin
  UserID := TImage(Sender).Hint;
  if UserID = '' then // sender is player status label
  begin
    UserID := TImagePanel(TLabel(Sender).Parent).Image.Hint;
  end;
  if UserID = '' then
    UserID := '-1';
  // check if inspector is looged in
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := 'SELECT * FROM BAR_LOGGINS WHERE IN_DATETIME IS NOT NULL AND OUT_DATETIME IS NULL AND USER_ID=' + UserID;
  FrmMain.OracleQuery1.Execute;
  if FrmMain.OracleQuery1.Eof then
  begin
    // login inspector
    FrmDealerSelect.ShowDealerForm('', '', '', '', UserID, false, true);
    FrmMain.SendEventToServer(EventTypeBarmanChange, '', '');
    GetLoggedBarman();
  end
  else
  begin
    // logout inspector
    if MessageDlg(_('Barman out?') + '(' + TImagePanel(TLabel(Sender).Parent).PlayerName.Caption + ')', mtWarning, [mbYes, mbNo], 0) = mrYes then
    begin
      UpdateDataToDB('BAR_LOGGINS', 'OUT_DATETIME=(SELECT SYSDATE FROM DUAL)', 'OUT_DATETIME IS NULL AND USER_ID=' + UserID);
      FrmMain.SendEventToServer(EventTypeBarmanChange, '', '');
      GetLoggedBarman();
    end;
  end;
end;

procedure TFrmMain.Login1Click(Sender: TObject);
begin
  pgc_Main.ActivePage := tbs_Login;
  Login1.Visible := false;
end;

procedure TFrmMain.Print1Click(Sender: TObject);
begin
  FrmPrintData.Show;
end;

procedure TFrmMain.About1Click(Sender: TObject);
begin
  FrmAbout.ShowModal;
end;

procedure TFrmMain.ActionList1Execute(Action: TBasicAction; var Handled: Boolean);
begin
  if ConnectedToDB and (LoggedUserId <> '') then
  BEGIN
    InsertDataIntoDB('USER_ACCESS', 'USER_ID, DATETIME, MODULE, COMPUTER_NAME', LoggedUserId + ', ' + 'to_date(''' + GetFormatedStringDateNOW(OracleSession1)
        + ''', ''dd.mm.yyyy hh24:mi:ss'')' + ', ' + '''' + MidStr(Action.Name, 5, Length(Action.Name)) + '''' + ', ' + '''' + ComputerName + '''');
  END;
end;

procedure TFrmMain.act_CanChangePasswordExecute(Sender: TObject);
begin
  frmChangePassword.ShowChangePassForm(stg_Users.Cells[0, stg_Users.Row]);
end;

procedure TFrmMain.act_CashGameReportExecute(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_ReportCashGame);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := act_CashGameReport.Caption;
  lbl_ReportName.Hint := 'CASH_GAMES';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.act_CountriesExecute(Sender: TObject);
begin
  ShowTabSheet(tbs_Countries);
  GetGridData(stg_Countries, SQL_Countries, true);
end;

procedure TFrmMain.act_LoginExecute(Sender: TObject);
begin
  ShowRightFormsForUserPrivileges(LoggedUserId);
  img_LogoSettings.Picture := GetImage('select IMAGE, IMAGE_TYPE from SETTINGS where id=1', OracleSession1);
  FrmMain.Menu := MainMenu;
  pnl_MainMenu.Visible := true;
end;

procedure TFrmMain.act_TicketsCashGameExecute(Sender: TObject);
begin
  if CheckCageOpened() then
  begin
    if frmCageCashGame = nil then
    begin
      frmCageCashGame := TfrmCageCashGame.Create(self);
      frmCageCashGame.Parent := tbs_CageCashGame;
      frmCageCashGame.Align := alClient;
      frmCageCashGame.BorderStyle := bsNone;
      frmCageCashGame.Visible := true;
      gnugettext.TranslateComponent(frmCageCashGame);
    end;
    SetActiveSubMenuButton(btn_TicketsCashGame);
    pgc_Main.ActivePage := tbs_CageCashGame;
    frmCageCashGame.GetCashGameData();
  end;
end;

procedure TFrmMain.act_TicketsExecute(ASender: TObject);
begin
  if CheckCageOpened() then
  begin
    HideAllDetailButtons(btn_MenuTickets);
    pgc_Main.ActivePage := tbs_Blank;
    btn_TicketsTournament.Visible := true;
    btn_TicketsCashGame.Visible := true;
    btn_CloseCage.Visible := true;
    btn_TicketsTournament.Top := 0;
    btn_TicketsTournament.Click;
  end;
end;

function TFrmMain.CheckCageOpened(): Boolean;
begin
  result := true;
  // CHECK CAGE OPENED
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('select * from(select * from (SELECT * FROM CAGE_INVENTORY order by datetime desc) where rownum=1) where opening=1');
  OracleQuery1.Execute;
  if OracleQuery1.Eof then
  begin
    // cage inventory first
    FrmCageInventory.IsOpening := true;
    if FrmCageInventory.ShowModal <> mrOK then
      result := false;
  end;
end;

procedure TFrmMain.act_TicketsTournamentExecute(Sender: TObject);
begin
  if CheckCageOpened() then
  begin
    FrmLoading.Show;
    FrmLoading.ProgressBar1.Position := 10;
    FrmLoading.Repaint;
    if frmCageTournament = nil then
    begin
      frmCageTournament := TfrmCageTournament.Create(self);
      frmCageTournament.Parent := tbs_CageTournament;
      frmCageTournament.Align := alClient;
      frmCageTournament.BorderStyle := bsNone;
      frmCageTournament.Visible := true;
      gnugettext.TranslateComponent(frmCageTournament);
      FrmLoading.ProgressBar1.Position := 40;
      FrmLoading.Repaint;
    end;
    SetActiveSubMenuButton(btn_TicketsTournament);
    pgc_Main.ActivePage := tbs_CageTournament;
    FrmLoading.ProgressBar1.Position := 50;
    FrmLoading.Repaint;
    frmCageTournament.stg_TournamentsSelectCell(self, 0, 2, CanSelect);
    frmCageTournament.dtp_DateChange(nil);
    FrmLoading.Close;
    frmCageTournament.GetLoggedCahiers();
  end;
end;

procedure TFrmMain.GetLoggedBarman();
var
  i: Integer;
begin
  if FrmSubjectImage = nil then
    FrmSubjectImage := TFrmSubjectImage.Create(self);
  for i := ComponentCount - 1 downto 0 do
  begin
    if Components[i] is TImagePanel then
    begin
      TImagePanel(Components[i]).Image.Picture := img_Inspector.Picture;
      TImagePanel(Components[i]).Image.OnClick := img_BarmanClick; ;
      TImagePanel(Components[i]).PlayerStatus.OnClick := img_BarmanClick;
      TImagePanel(Components[i]).PlayerName.OnClick := img_BarmanClick;
      TImagePanel(Components[i]).Caption := '';
      TImagePanel(Components[i]).PlayerName.Caption := '';
      TImagePanel(Components[i]).Image.Hint := '';
    end;
  end;
  FrmMain.OracleQuery1.Session := OraSessMainUtils;
  FrmMain.OracleQuery1.Close;
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('SELECT * FROM GET_LOGGED_BARMANS');
  FrmMain.OracleQuery1.Execute;
  img_Barman.Image.Picture := img_Inspector.Picture;
  if not FrmMain.OracleQuery1.Eof then
  begin
    img_Barman.PlayerName.Caption := VarToStr(FrmMain.OracleQuery1.Field('SUBJECT'));
    FrmSubjectImage.img_TakenPhoto.Picture.Assign(uUtils.GetImage(SQL_User_Picture + VarToStr(FrmMain.OracleQuery1.Field('USER_ID')), OraSessMainUtils, false));
    FrmSubjectImage.img_BlackHole.BringToFront;
    img_Barman.Image.Transparent := true;
    img_Barman.Image.Picture.Bitmap.Assign(FrmSubjectImage.GetFormImage);
    FrmSubjectImage.GetFormImage.FreeImage;
    img_Barman.Image.Picture.Bitmap.PixelFormat := pf24Bit;
    img_Barman.Image.Hint := VarToStr(FrmMain.OracleQuery1.Field('USER_ID'));
  end;
end;

procedure TFrmMain.act_PlayerPointsExecute(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_PlayerPoints);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := act_PlayerPoints.Caption;
  lbl_ReportName.Hint := 'PLAYER_POINTS';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.act_PlayersExecute(Sender: TObject);
begin
  LockWindowUpdate(self.handle);
  if FraPlayersMain = nil then
  begin
    FraPlayersMain := TFraPlayers.Create(self);
    FraPlayersMain.Parent := tbs_Players;
    FraPlayersMain.Align := alClient;
    gnugettext.TranslateComponent(FraPlayersMain);
  end;
  HideAllDetailButtons(btn_MenuPlayers);
  ShowTabSheet(tbs_Players);
  FraPlayersMain.Parent := tbs_Players;
  GetGridData(FraPlayersMain.stg_Players, SQL_Players, false);
  FraPlayersMain.stg_Players.ColWidths[1] := 90;
  FraPlayersMain.stg_Players.ColWidths[2] := 90;
  FraPlayersMain.stg_Players.ColWidths[3] := 65;
  FraPlayersMain.stg_Players.ColWidths[4] := 70;
  FraPlayersMain.stg_Players.ColWidths[5] := 95;
  FraPlayersMain.stg_Players.ColWidths[6] := 95;
  FraPlayersMain.stg_Players.ColWidths[7] := 90;
  FraPlayersMain.stg_Players.ColWidths[8] := 135;
  FraPlayersMain.stg_Players.ColWidths[9] := 60;
  FraPlayersMain.stg_PlayersSelectCell(self, 0, 2, CanSelect);
  SelectGridRow(FraPlayersMain.stg_Players, 2);
  LockWindowUpdate(0);
end;

procedure TFrmMain.act_PrepareCashGameExecute(Sender: TObject);
begin
  HideAllDetailButtons(btn_MenuPrepareCashGame);
  ShowTabSheet(tbs_CashGames);
  GetGridData(FrmMain.stg_CashGames, SQL_CashGames, false);
  stg_CashGames.ColWidths[1] := 90;
  stg_CashGames.ColWidths[2] := 100;
  stg_CashGames.ColWidths[3] := 150;
  stg_CashGames.ColWidths[4] := 90;
  stg_CashGames.ColWidths[5] := 80;
  stg_CashGames.ColWidths[6] := 80;
  stg_CashGames.ColWidths[7] := 80;
  stg_CashGamesSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.act_PrepareTournamentExecute(Sender: TObject);
begin
  LockWindowUpdate(self.handle);
  HideAllDetailButtons(btn_MenuPrepareTournament);
  ShowTabSheet(tbs_Tournaments);
  GetGridData(stg_Tournaments, SQL_Tournaments, false);
  stg_Tournaments.ColWidths[1] := 120;
  stg_Tournaments.ColWidths[2] := 120;
  stg_Tournaments.ColWidths[3] := 50;
  stg_Tournaments.ColWidths[4] := 50;
  stg_Tournaments.ColWidths[5] := 50;
  stg_Tournaments.ColWidths[6] := 50;
  stg_Tournaments.ColWidths[7] := 50;
  stg_Tournaments.ColWidths[8] := 50;
  stg_Tournaments.ColWidths[9] := 60;
  stg_Tournaments.ColWidths[10] := 45;
  stg_Tournaments.ColWidths[11] := 50;
  stg_Tournaments.ColWidths[12] := 60;
  SelectGridRow(stg_Tournaments, 2);
  stg_TournamentsSelectCell(self, 0, 2, CanSelect);
  self.Refresh;
  LockWindowUpdate(0);
end;

procedure TFrmMain.act_ProfilesExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_Profiles);
  ShowTabSheet(tbs_Profiles);
  GetGridData(stg_Profiles, SQL_Profiles, true);
  stg_ProfilesSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.act_RoundTypesExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_RoundTypes);
  ShowTabSheet(tbs_RoundTypes);
  GetGridData(stg_RoundTypes, SQL_RoundTypes, true);
  stg_RoundTypes.ColWidths[2] := 100;
  stg_RoundTypes.ColWidths[1] := stg_RoundTypes.Width - stg_RoundTypes.ColWidths[2];
  stg_RoundTypesSelectCell(self, 0, 2, CanSelect);
  SelectGridRow(stg_RoundTypes, 2);
  self.Repaint;
end;

procedure TFrmMain.act_DataTrackingExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_ReportDataTracking);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := act_DataTracking.Caption;
  lbl_ReportName.Hint := 'DATA_TRACKING';
  btn_GetReportData.Click;
end;

procedure TFrmMain.act_DrinksExecute(Sender: TObject);
begin
  ShowTabSheet(tbs_Drinks);
  GetGridData(stg_Drinks, SQL_Drinks, true);
  GetGridData(stg_DrinkTypes, SQL_DrinkTypes, true);
  SetActiveSubMenuButton(btn_MenuDrinks);
end;

procedure TFrmMain.act_GeneralExecute(Sender: TObject);
begin
  HideAllDetailButtons(btn_MenuGeneral);
  ShowTabSheet(tbs_Blank);
  btn_WinDistribution.Visible := true;
  btn_Tables.Visible := true;
  btn_RoundTypes.Visible := true;
  btn_MenuCountries.Visible := true;
  btn_MenuEMailing.Visible := true;
  btn_TournamentTypes.Visible := true;
  btn_RakeValues.Visible := true;
  btn_CasinoInventory.Visible := true;
end;

function TFrmMain.SearchStringGrid(Grid: TStringGrid; TextVal: string; GridRow: Integer): Integer; // row
var
  nCol: Integer;
  nRow: Integer;
begin
  if TextVal <> '' then
  begin
    if (PrevGridSearchTime + 3000) > TimeStampToMSecs(DateTimeToTimeStamp(now)) then
    begin
      SearchGridStr := SearchGridStr + TextVal;
    end
    else
    begin
      SearchGridStr := TextVal;
    end;
    PrevGridSearchTime := TimeStampToMSecs(DateTimeToTimeStamp(now));
    LockWindowUpdate(Grid.handle);
    if GridRow = -1 then
      GridRow := GridRow + Grid.FixedRows;
    for nRow := GridRow + 1 to Grid.RowCount - 1 do
      for nCol := 1 to Grid.ColCount - 1 do
        if pos(uppercase(TextVal), uppercase(Grid.Cells[nCol, nRow])) > 0 then
        begin
          Grid.Row := nRow;
          result := nRow;
          LockWindowUpdate(0);
          exit;
        end;
    LockWindowUpdate(0);
    if GridRow <> -1 then
      ShowMessage(_('No more hits'));
  end;
end;

function TFrmMain.GetCharFromVirtualKey(Key: Word): string;
var
  keyboardState: TKeyboardState;
  asciiResult: Integer;
begin
  GetKeyboardState(keyboardState);

  SetLength(result, 2);
  asciiResult := ToAscii(Key, MapVirtualKey(Key, 0), keyboardState, @result[1], 0);
  case asciiResult of
    0:
      result := '';
    1:
      SetLength(result, 1);
    2:
      ;
  else
    result := '';
  end;
end;

procedure TFrmMain.act_HallExecute(Sender: TObject);
begin
  try
    LockWindowUpdate(self.handle);
    HideAllDetailButtons(btn_MenuHallView);
    FrmLoading.Repaint;
    HideAllDetailButtons(Sender);
    ShowTabSheet(tbs_Hall);
    if m_FrmHall = nil then
    begin
      m_FrmHall := TFrmHall.Create(self);
      m_FrmHall.Parent := tbs_Hall;
      m_FrmHall.Align := alClient;
      m_FrmHall.Show;
      m_FrmHall.Init(OracleSession1);
      gnugettext.TranslateComponent(m_FrmHall);
      m_FrmHall.ClientSocket1.Port := ClientSocket1.Port;
      m_FrmHall.ClientSocket1.Host := ClientSocket1.Host;
      if ParamStr(3) <> 'LOGIN' then
        m_FrmHall.ClientSocket1.Active := true;
    end
    else
    begin
      m_FrmHall.GetData(OracleSession1);
    end;
    LockWindowUpdate(0);
  except
    on E: Exception do
    begin
      FrmLoading.Close;
    end;
  end;
end;

procedure TFrmMain.act_SettingsExecute(Sender: TObject);
begin
  ShowTabSheet(tbs_Settings);
  if ConnectedToDB then
  begin
    edt_Currency_Symbol.Text := Currency_Symbol;
    OracleQuery1.SQL.Clear;
    OracleQuery1.SQL.Text := ('SELECT * FROM SETTINGS');
    OracleQuery1.Execute;
    edt_DisplaySeatingTime.Text := VarToStr(OracleQuery1.Field('DISPLAY_SEATING_TIME'));
    edt_DisplayRegisteringTime.Text := VarToStr(OracleQuery1.Field('DISPLAY_REGISTERING_TIME'));
    if OracleQuery1.Field('GAME_DAY_START') <> null then
    begin
      dtp_GDTimeStart.Time := OracleQuery1.Field('GAME_DAY_START');
    end;
  end
  else
  begin
    Login1.Visible := true;
  end;
end;

procedure TFrmMain.act_TournamentReportsExecute(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  SetActiveSubMenuButton(btn_ReportTournament);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := act_TournamentReports.Caption;
  lbl_ReportName.Hint := 'TOURNAMENTS';
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  btn_GetReportData.Click;
  FrmLoading.Close;
end;

procedure TFrmMain.DBGridFormatNumber(Sender: TField; var Text: string; DisplayText: Boolean);
begin
  Text := FormatFloat('#,##0.00', Sender.AsFloat);
end;

procedure TFrmMain.act_TournamentTypesExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_Profiles);
  ShowTabSheet(tbs_TournamentTypes);
  GetGridData(stg_TournamentTypes, SQL_TournamentTypes, true);
  stg_TournamentTypesSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.act_TablesExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_Tables);
  ShowTabSheet(tbs_Tables);
  GetGridData(stg_Tables, SQL_Tables, true);
  GetGridData(stg_TableZones, SQL_TableZones, true);
end;

procedure TFrmMain.act_UserAccessExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_UserAccess);
  dtp_ReportFrom.Date := now();
  dtp_ReportTo.Date := now();
  ShowTabSheet(tbs_Reports);
  lbl_ReportName.Caption := act_UserAccess.Caption;
  lbl_ReportName.Hint := 'USER_ACCESS';
  btn_GetReportData.Click;
end;

procedure TFrmMain.act_UsersExecute(Sender: TObject);
begin
  LockWindowUpdate(self.handle);
  HideAllDetailButtons(btn_MenuUsers);
  ShowTabSheet(tbs_Users);
  btn_Profiles.Visible := true;
  GetGridData(stg_ProfilesFilter, 'SELECT -1 AS ID, ''ALL'' AS PROFILE FROM DUAL UNION ALL SELECT * FROM(SELECT * FROM PROFILES WHERE ID<>1 ORDER BY NAME ASC)', true);
  stg_ProfilesFilterSelectCell(self, 0, 2, CanSelect);
  stg_UsersSelectCell(self, 0, 2, CanSelect);
  LockWindowUpdate(0);
end;

procedure TFrmMain.act_WinDistributionExecute(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_WinDistribution);
  ShowTabSheet(tbs_WinDistribution);
  GetGridData(stg_WinDistribution, SQL_WinDist, true);
  stg_WinDistributionSelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.ApplicationEvents1Exception(Sender: TObject; E: Exception);
var
  TableNm: string;
begin
  if FrmLoading <> nil then
  begin
    if FrmLoading.Showing then
    begin
      FrmLoading.Close;
    end;
  end;
  if (pos('ORA-01400', E.Message) > 0) or (pos('ORA-01407', E.Message) > 0) then
  begin
    TableNm := MidStr(E.Message, pos('.', E.Message) + 1, Length(E.Message));
    TableNm := MidStr(TableNm, pos('.', TableNm) + 1, Length(TableNm));
    TableNm := MidStr(TableNm, 0, pos(')', TableNm) - 1);
    TableNm := ReplaceStr(TableNm, '"', '');
  end;
  if (pos('ORA-01400', E.Message) > 0) or (pos('ORA-01407', E.Message) > 0) then
  begin
    // insert null      // update null
    TableNm := MainUtils.GetFieldNameText(TableNm);
    ShowMessage(_('Field') + ' (' + TableNm + ') ' + _('must have value'));
  end
  else if (pos('ORA', E.Message) > 0) then
  begin
    ShowMessage(_('Database error occured.' + #13#10 + E.Message));
    if OraSessMainUtils.CheckConnection(false) = ccError then
    begin
      ShellExecute(0, 'open', Pchar(Application.ExeName), nil, nil, SW_SHOWNORMAL);
      ExitProcess(0);
    end;
  end
  else if (pos('ORA-00001', E.Message) > 0) and (pos('TOURNAMENTS', E.Message) > 0) then
  begin
    // on edit or insert tournament
    ShowMessage(_('Tournament name already exists!'));
  end
  else
  begin
    ShowMessage(E.Message);
    SaveToErrLog(E.Message);
  end;
end;

procedure TFrmMain.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
  i: SmallInt;
begin
  if (Msg.message = WM_MOUSEWHEEL) and (pgc_Main.ActivePage = tbs_Reports) then
  begin

    begin
      if Msg.wParam > 0 then
        SendMessage(ActiveControl.handle, WM_KEYDOWN, VK_UP, 0)
      else
        SendMessage(ActiveControl.handle, WM_KEYDOWN, VK_DOWN, 0);
      Handled := true;
    end;
    stg_GridReportCellClick(nil);
    { Msg.message := WM_KEYDOWN;
      Msg.lParam := 0;
      i := HiWord(Msg.wParam);
      if i > 0 then
      Msg.wParam := VK_UP
      else
      Msg.wParam := VK_DOWN;
      stg_GridReportCellClick(nil); }
    // Handled := false;
  end;
end;

procedure TFrmMain.SaveToErrLog(ErrorMsg: string);
var
  ErrorLogFileName: string;
  ErrorFile: TextFile;
  ErrorData: string;
begin
  ErrorLogFileName := ChangeFileExt(ExtractFileName(Application.ExeName), '.error.log');
  AssignFile(ErrorFile, ErrorLogFileName);
  // either create an error log file, or append to an existing one
  if FileExists(ErrorLogFileName) then
    Append(ErrorFile)
  else
    Rewrite(ErrorFile);
  try
    // add the current date/time and the exception message to the log
    ErrorData := Format('%s - %s', [DateTimeToStr(now), ErrorMsg]);
    WriteLn(ErrorFile, ErrorData);
  finally
    CloseFile(ErrorFile)
  end;
end;

procedure TFrmMain.btn_ArchiveOldDataClick(Sender: TObject);
var
  Tournaments, Tickets: Integer;
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 10;
  FrmLoading.Repaint;
  // TOURNAMENTS
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('UPDATE TOURNAMENTS SET ARCHIVE=1 WHERE ID IN (SELECT ID FROM GETTICKETTOURNAMENTS WHERE STATUS=''FINISHED'' AND EVENT_START<(SELECT SYSDATE FROM DUAL)-2) AND ARCHIVE=0');
  OracleQuery1.Execute;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  Tournaments := OracleQuery1.RowsProcessed;
  OracleSession1.Commit;
  FrmLoading.ProgressBar1.Position := 50;
  FrmLoading.Repaint;
  // TICKETS
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := (
    'UPDATE TICKETS SET ARCHIVE=1 WHERE TOURNAMENT_ID IN (SELECT ID FROM GETTICKETTOURNAMENTS WHERE STATUS=''FINISHED'' AND EVENT_START<(SELECT SYSDATE FROM DUAL)-2) AND ARCHIVE=0');
  OracleQuery1.Execute;
  FrmLoading.ProgressBar1.Position := 70;
  FrmLoading.Repaint;
  Tickets := OracleQuery1.RowsProcessed;
  OracleSession1.Commit;
  FrmLoading.ProgressBar1.Position := 90;
  FrmLoading.Repaint;
  FrmLoading.Close;
  ShowMessage(_('Archived data:' + #13#10 + 'Tournaments: ' + inttostr(Tournaments) + #13#10 + 'Tickets: ' + inttostr(Tickets)));
end;

procedure TFrmMain.btn_CasinoInventoryClick(Sender: TObject);
begin
  SetActiveSubMenuButton(btn_CasinoInventory);
  ShowTabSheet(tbs_CasinoInventory);
  GetGridData(stg_CasinoInventory, SQL_CasinoInventory, true);
  stg_CasinoInventorySelectCell(self, 0, 2, CanSelect);
end;

procedure TFrmMain.btn_ChangePictureClick(Sender: TObject);
var
  FileExt: string;
begin
  if MessageDlg(_('Do you realy want to change picture?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    OpenPictureDialog1.Execute();
    FileExt := ReplaceStr(uppercase(ExtractFileExt(OpenPictureDialog1.filename)), '.', '');
    // ---
    SavePhotoToDB(OpenPictureDialog1.filename, FileExt, '', false);
  end;
  if pgc_Main.ActivePage = tbs_Settings then
  begin
    img_LogoSettings.Picture := GetImage('select IMAGE, IMAGE_TYPE from SETTINGS where id=1', OracleSession1);
  end;
end;

procedure TFrmMain.SavePhotoToDB(PhotoSource, FileExt, ObjectID: string; Resize: Boolean);
var
  ImageBlob: TLobLocator;
  TableName, SubjectID, PhotoFileName: string;
  JPG: TJPEGImage;
  PNG: TPNGImage;
begin
  PhotoFileName := 'SubjectPhoto.PNG';
  ImageBlob := TLobLocator.CreateTemporary(OraSessMainUtils, otBLOB, true);
  if (pgc_Main.ActivePage = tbs_Players) then
  begin
    TableName := 'PLAYERS';
    SubjectID := FraPlayersMain.stg_Players.Cells[0, FraPlayersMain.stg_Players.Row];
  end
  else if pgc_Main.ActivePage = tbs_Users then
  begin
    TableName := 'USERS';
    SubjectID := stg_Users.Cells[0, stg_Users.Row];
  end
  else if pgc_Main.ActivePage = tbs_Settings then
  begin
    TableName := 'SETTINGS';
    SubjectID := '1';
  end
  else if (pgc_Main.ActivePage = tbs_CageTournament) or (pgc_Main.ActivePage = tbs_CageCashGame) then
  begin
    TableName := 'PLAYERS';
    SubjectID := ObjectID;
  end
  else if (pgc_Main.ActivePage = tbs_Countries) then
  begin
    TableName := 'COUNTRIES';
    SubjectID := stg_Countries.Cells[0, stg_Countries.Row];
  end;
  OraQueryMainUtils.SQL.Clear;
  OraQueryMainUtils.SQL.Text := ('update ' + TableName + ' set image=:IMAGE, image_type=' + '''' + FileExt + '''' + ' where id=' + SubjectID);
  OraQueryMainUtils.DeclareVariable(':IMAGE', otBLOB);
  OraQueryMainUtils.SetComplexVariable(':IMAGE', ImageBlob);
  // --------------------------
  if uppercase(FileExt) = 'JPEG' then
    FileExt := 'JPG';
  if FileExt = 'PNG' then
  begin
    // --- picture resizing
    PNG := TPNGImage.Create();
    PNG.Transparent := true;
    PNG.LoadFromFile(PhotoSource);
    PNG.SaveToFile(PhotoFileName);
    // ----
    ImageBlob.LoadFromFile(PhotoFileName);
    OraQueryMainUtils.Execute;
    OraSessMainUtils.Commit;
    FrmMain.OracleQuery1.Clear;
    // save small image
    if TableName = 'PLAYERS' then
    begin
      OraQueryMainUtils.SQL.Clear;
      OraQueryMainUtils.SQL.Text := ('update ' + TableName + ' set IMAGE_SMALL=:IMAGE, image_type=' + '''' + FileExt + '''' + ' where id=' + SubjectID);
      OraQueryMainUtils.DeclareVariable(':IMAGE', otBLOB);
      // --- picture resizing
      PNG := TPNGImage.Create();
      PNG.Transparent := true;
      PNG.LoadFromFile(PhotoSource);
    end;
    PNG.SaveToFile(PhotoFileName);
  end
  else if FileExt = 'JPG' then
  begin
    JPG := TJPEGImage.Create();
    JPG.Transparent := true;
    JPG.LoadFromFile(PhotoSource);
    JPG.SaveToFile(PhotoFileName);
    // ---
    OraQueryMainUtils.SetComplexVariable(':IMAGE', ImageBlob);
    ImageBlob.LoadFromFile(PhotoFileName);
    OraQueryMainUtils.Execute;
    OraSessMainUtils.Commit;
    OraQueryMainUtils.Clear;
    // save small image
    if TableName = 'PLAYERS' then
    begin
      OraQueryMainUtils.SQL.Clear;
      OraQueryMainUtils.SQL.Text := ('update ' + TableName + ' set IMAGE_SMALL=:IMAGE, image_type=' + '''' + FileExt + '''' + ' where id=' + SubjectID);
      OraQueryMainUtils.DeclareVariable(':IMAGE', otBLOB);
      // --- picture resizing
      JPG := TJPEGImage.Create();
      JPG.Transparent := true;
      JPG.LoadFromFile(PhotoSource);
      if Resize then
      begin
        JPG := resizeImage(JPG, 106, 80);
      end;
    end;
    JPG.SaveToFile(PhotoFileName);
  end;
  // ----
  ImageBlob.LoadFromFile(PhotoFileName);
  OraQueryMainUtils.SetComplexVariable(':IMAGE', ImageBlob);
  OraQueryMainUtils.Execute;
  OraSessMainUtils.Commit;
  OraQueryMainUtils.Clear;
  FreeAndNil(ImageBlob);
  FreeAndNil(uUtils.resizeBmpImg);
  FreeAndNil(uUtils.resizeJpgImg);
  DeleteFile(PhotoFileName);
end;

procedure TFrmMain.btn_LoginCloseClick(Sender: TObject);
begin
  CloseApplication();
end;

procedure TFrmMain.UpdateRebuyOrAddon(IsCashGame, IsRebuy: Boolean; TicketID, Value: string);
begin
  if IsCashGame then
  begin
    // CHECK IF REBUY ALREADY FINISHED ON OTHER CAGE

    UpdateDataToDB('CASH_GAME_TICKET_REBUYS', 'VALUE=' + Value + ',' + 'ACCEPT_DATETIME=(SELECT SYSDATE FROM DUAL)', 'ID=' + TicketID);
  end
  else
  begin
    if IsRebuy then
    begin
      UpdateDataToDB('TICKET_REBUY', 'VALUE=' + Value, 'ID=' + TicketID);
    end
    else
    begin
      UpdateDataToDB('TICKET_ADDON', 'VALUE=' + Value, 'ID=' + TicketID);
    end;
  end;
end;

procedure TFrmMain.btn_LoginOKClick(Sender: TObject);
var
  ServerTime: string;
begin
  OracleSession1.LogOn;
  OracleQuery1.Session := OracleSession1;
  SetOracleSession(self, OracleSession1, edt_Username.Text, edt_Password.Text);
  ServerTime := GetFormatedStringDateNOW(OracleSession1);
  if abs(now - StrToDateTime(ServerTime)) > 1 / 1440 * 10 then
  // TEN minutes max
  begin
    ShowMessage(_('Client time is not synchronized with server time. Adjust time.' + #13#10 + 'Server time:' + ' ' + ServerTime));
  end;
  ConnectedToDB := true;
  Currency_Symbol := GetCurrencySymbol(OracleSession1);
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('select id, name, surname from USERS where username=' + '''' + edt_Username.Text + '''' + ' and password=' + '''' + edt_Password.Text + '''');
  OracleQuery1.Execute;
  edt_Username.Text := '';
  edt_Password.Text := '';
  if (OracleQuery1.RowCount = 0) then
  begin
    MessageDlg(_('Username or Password not correct!'), mtWarning, [mbOK], 0);
  end
  else
  begin
    LoggedUserId := OracleQuery1.Field(0);
    StatusBar1.Panels[0].Text := _('User:') + ' ' + OracleQuery1.Field(1) + ' ' + OracleQuery1.Field(2);
    act_Login.Enabled := true;
    act_Login.Visible := true;
    act_Login.Execute;
  end;
  HideAllDetailButtons(Sender);
end;

procedure TFrmMain.btn_LogoutClick(Sender: TObject);
begin
  if MessageDlg(_('Do you really want to Logout?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    LoggedUserId := '';
    StatusBar1.Panels[0].Text := '';
    pnl_MainMenu.Visible := false;
    pgc_Main.ActivePage := tbs_Login;
  end;
end;

procedure TFrmMain.btn_DeleteClick(Sender: TObject);
begin
  if MessageDlg(_('Delete record?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    DeleteDataFromDB('USERS', 'ID=' + stg_Users.Cells[0, stg_Users.Row]);
    GetGridData(stg_Users, SQL_Users, false);
  end;
end;

procedure TFrmMain.btn_DeletePictureClick(Sender: TObject);
var
  TableName, SubjectID: string;
begin
  if pgc_Main.ActivePage = tbs_Players then
  begin
    TableName := 'PLAYERS';
    SubjectID := FraPlayersMain.stg_Players.Cells[0, FraPlayersMain.stg_Players.Row];
  end
  else if pgc_Main.ActivePage = tbs_Users then
  begin
    TableName := 'USERS';
    SubjectID := stg_Users.Cells[0, stg_Users.Row];
  end
  else if pgc_Main.ActivePage = tbs_Users then
  begin
    TableName := 'COUNTRIES';
    SubjectID := stg_Countries.Cells[0, stg_Countries.Row];
  end;
  if MessageDlg(_('Delete image?'), mtWarning, [mbYes, mbNo], 0) = mrYes then
  begin
    UpdateDataToDB(TableName, 'IMAGE='''', IMAGE_TYPE=''''', 'ID=' + SubjectID);
  end;
end;

procedure TFrmMain.btn_DrinkOrdersClick(Sender: TObject);
begin
  ShowTabSheet(tbs_DrinkOrders);
  SetActiveSubMenuButton(btn_DrinkOrders);
  GetGridData(stg_DrinkOrders, SQL_DrinkOrders + ' WHERE COMPLETED<>1 ORDER BY DATETIME ASC', true);
  stg_DrinkOrders.ColWidths[1] := 130;
  stg_DrinkOrders.ColWidths[2] := 50;
  stg_DrinkOrders.ColWidths[3] := 50;
  stg_DrinkOrders.ColWidths[4] := 120;
  stg_DrinkOrders.ColWidths[5] := 150;
  stg_DrinkOrders.ColWidths[6] := -1; // COMPLETED
  stg_DrinkOrders.ColWidths[7] := 70; // PRICE
  // ------------
  // released drinks
  GetGridData(stg_ReleasedDrinks, SQL_DrinkOrders + ' where completed=1 and datetime between (select * from GET_GD_START_TIME) and (select * from GET_GD_START_TIME)+1', false);
  stg_ReleasedDrinks.ColWidths[1] := 130;
  stg_ReleasedDrinks.ColWidths[2] := 50;
  stg_ReleasedDrinks.ColWidths[3] := 50;
  stg_ReleasedDrinks.ColWidths[4] := 120;
  stg_ReleasedDrinks.ColWidths[5] := 150;
  stg_ReleasedDrinks.ColWidths[6] := -1; // COMPLETED
  stg_ReleasedDrinks.ColWidths[7] := 70; // PRICE
  GetLoggedBarman();
end;

procedure TFrmMain.btn_DuplicateClick(Sender: TObject);
begin
  uFrmEditUsers.ShowForm(true, true, stg_Users.Cells[0, stg_Users.Row]);
end;

procedure TFrmMain.CloseApplication();
begin
  if MessageDlg(_('Close application?'), mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  begin
    Close;
  end;
end;

procedure TFrmMain.ddd1Click(Sender: TObject);
begin
  if LoggedUserId = '' then
  begin
    ChangePassword1.Visible := false;
  end
  else
  begin
    ChangePassword1.Visible := true;
  end;
end;

procedure TFrmMain.btn_EditClick(Sender: TObject);
begin
  uFrmEditUsers.ShowForm(true, false, stg_Users.Cells[0, stg_Users.Row]);
end;

procedure TFrmMain.btn_GetReportDataClick(Sender: TObject);
var
  WhereCond, Query: string;
begin
  if lbl_ReportName.Hint = 'DEALER_ACTIVITY' then
  begin
    pnl_ReportDetail.Visible := false;
    WhereCond := 'where OUT_DATETIME IS NULL OR trunc(IN_DATETIME) between ' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and ' + '''' + DateToStr(dtp_ReportTo.Date) + '''';
    Query := ('SELECT * FROM GET_SUBJECT_ACTIVITY ' + WhereCond + OrderReportBy);
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    // ----
    stg_GridReport.Columns[0].Width := 120;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 60;
    stg_GridReport.Columns[3].Width := 60;
    stg_GridReport.Columns[4].Width := 130;
  end
  ELSE if lbl_ReportName.Hint = 'EVENTS' then
  begin
    pnl_ReportDetail.Visible := true;
    WhereCond := 'where trunc(DATETIME) between ' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and ' + '''' + DateToStr(dtp_ReportTo.Date) + '''';
    Query := ('SELECT * FROM GET_EVENTS ' + WhereCond + OrderReportBy);
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    // ----
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 100;
    stg_GridReport.Columns[3].Width := 90;
    stg_GridReport.Columns[4].Width := 100;
    stg_GridReport.Columns[5].Width := 40;
    stg_GridReport.Columns[6].Width := 100;
    stg_GridReport.Columns[7].Width := 100;
  end
  ELSE if lbl_ReportName.Hint = 'CASH_GAMES' then
  begin
    pnl_ReportDetail.Visible := true;
    WhereCond := ' where cgt.deleted=0 and trunc(gaming_day)>=' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and trunc((SELECT SYSDATE FROM DUAL)+' + EventEndDelay + ')<=' + '''' + DateToStr
      (dtp_ReportTo.Date) + ' ' + '''';
    Query := ('select * from (SELECT CG.ID, OPEN, CLOSE, trunc(GAMING_DAY) AS GAMING_DAY, NAME, SUM(INPUT_VALUE) AS INPUT, SUM(OUTPUT_VALUE) AS OUTPUT, RAKE_ID, SUM(OUTPUT_VALUE)-SUM(INPUT_VALUE)' +
        ' AS WIN FROM CASH_GAMES CG LEFT JOIN CASH_GAME_TICKETS CGT ON CG.ID=CGT.CASH_GAME_ID ' + ' LEFT JOIN CASH_GAME_OPENS CGO ON CGO.CASH_GAME_ID=CG.ID ' + WhereCond +
        ' GROUP BY  OPEN, CLOSE, GAMING_DAY, NAME, RAKE_ID, CG.ID  ' + OrderReportBy + ') UNION ALL' +
        ' SELECT NULL, NULL, NULL, NULL, NULL, SUM(INPUT_VALUE), SUM(OUTPUT_VALUE), NULL, SUM(OUTPUT_VALUE)-SUM(INPUT_VALUE) FROM CASH_GAMES CG JOIN CASH_GAME_TICKETS CGT ON CG.ID=CGT.CASH_GAME_ID '
        + WhereCond);
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    // ----
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 120;
    stg_GridReport.Columns[3].Width := 70;
    stg_GridReport.Columns[4].Width := 140;
    stg_GridReport.Columns[5].Width := 90;
    stg_GridReport.Columns[6].Width := 90;
    stg_GridReport.Columns[7].Width := 90;
    stg_GridReport.Columns[8].Width := 90;
    stg_GridReport.DataSource.DataSet.FieldByName('INPUT').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('OUTPUT').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('WIN').OnGetText := DBGridFormatNumber;
  end
  else if lbl_ReportName.Hint = 'PLAYER_POINTS' then
  begin
    pnl_ReportDetail.Visible := false;
    Query :=
      ' SELECT pl.id, pl.NAME||'' ''||SURNAME AS PLAYER, BIRTH_DATE, SUM(BUY_IN) AS BUY_IN,SUM(PAY_VALUE) AS WIN_VALUE,SUM(REBUY_VALUE) AS REBUY, SUM(ADDON_VALUE) AS ADDON, CASH_IN, cash_out, cash_rebuy FROM PLAYERS PL' +
      ' LEFT JOIN TICKETS TI ON PL.ID=TI.PLAYER_ID' + ' LEFT JOIN (SELECT SUM(VALUE) AS REBUY_VALUE, TICKET_ID FROM TICKET_REBUY GROUP BY TICKET_ID) TR ON TR.TICKET_ID=TI.ID' +
      ' LEFT JOIN (SELECT SUM(VALUE) AS ADDON_VALUE , TICKET_ID FROM TICKET_ADDON GROUP BY TICKET_ID) TA ON TA.TICKET_ID=TI.ID' +
      ' LEFT JOIN (SELECT player_id, sum(input_value) as cash_in, sum(output_value) as cash_out, sum(rebuy_value) as cash_rebuy FROM CASH_GAME_TICKETS CGT JOIN (SELECT SUM(VALUE) AS REBUY_VALUE, CASH_GAME_TICKET_ID '
      + ' FROM CASH_GAME_TICKET_REBUYS GROUP BY CASH_GAME_TICKET_ID) CGTR ON CGT.ID=CGTR.CASH_GAME_TICKET_ID group by player_id) CGT ON CGT.PLAYER_ID=PL.ID';
    Query := Query + ' where ti.deleted=0 ';
    Query := Query + ' and trunc(ti.datetime)>=' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and trunc((SELECT SYSDATE FROM DUAL)+' + EventEndDelay + ')<=' + '''' + DateToStr
      (dtp_ReportTo.Date) + '''';
    Query := Query + ' group by pl.id, pl.name, surname, birth_date, CASH_IN, cash_out, cash_rebuy ' + OrderReportBy;
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 130;
    stg_GridReport.Columns[2].Width := 70;
    stg_GridReport.Columns[3].Width := 70;
    stg_GridReport.Columns[4].Width := 70;
    stg_GridReport.Columns[5].Width := 70;
    stg_GridReport.Columns[6].Width := 70;
    stg_GridReport.Columns[7].Width := 70;
    stg_GridReport.Columns[8].Width := 70;
    stg_GridReport.Columns[9].Width := 70;
  end
  else if lbl_ReportName.Hint = 'DRINK_ORDERS' then
  begin
    pnl_ReportDetail.Visible := false;
    Query := 'select * from (' + SQL_DrinkOrders;
    WhereCond := ' where completed=1 and trunc(datetime)>=' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and trunc((SELECT SYSDATE FROM DUAL)+' + EventEndDelay + ')<=' + '''' + DateToStr
      (dtp_ReportTo.Date) + '''';
    Query := Query + WhereCond + OrderReportBy;
    Query := Query + ') UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, SUM(PRICE) FROM DRINK_ORDERS DRO JOIN DRINKS DR ON DRO.DRINK_ID=DR.ID ';
    Query := Query + WhereCond;
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 130;
    stg_GridReport.Columns[2].Width := 50;
    stg_GridReport.Columns[3].Width := 50;
    stg_GridReport.Columns[4].Width := 120;
    stg_GridReport.Columns[5].Width := 150;
    stg_GridReport.Columns[6].Width := 70;
    stg_GridReport.Columns[7].Width := 70;
  end
  else if lbl_ReportName.Hint = 'USER_ACCESS' then
  begin
    pnl_ReportDetail.Visible := false;
    WhereCond := 'where trunc(DATETIME) between ' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and ' + '''' + DateToStr(dtp_ReportTo.Date) + '''';
    Query := 'SELECT UA.ID, UA.DATETIME, UA.MODULE, UA.COMPUTER_NAME, U.NAME, U.USERNAME  FROM USER_ACCESS UA JOIN USERS U ON UA.USER_ID=U.ID ' + WhereCond + OrderReportBy;
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 150;
    stg_GridReport.Columns[3].Width := 150;
    stg_GridReport.Columns[4].Width := 100;
    stg_GridReport.Columns[5].Width := 100;
  end
  else if lbl_ReportName.Hint = 'TOURNAMENTS' then
  begin
    pnl_ReportDetail.Visible := true;
    WhereCond := ' where trunc(event_start)>=' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and trunc(event_start)<=' + '''' + DateToStr(dtp_ReportTo.Date) + ' ' + '''';
    Query := ('select * from (select ID, TO_CHAR(EVENT_START,''DD.MM.YY HH24:MI DY'') AS EVENT_START, NAME, BUY_IN, PLAYERS, MONEY_PRIZE, SUM_FEE, SUM_RAKE from GETTICKETTOURNAMENTS ' + WhereCond +
        OrderReportBy + ') union all ' + ' select null,  null, null, sum(BUY_IN), NULL, SUM(MONEY_PRIZE), SUM(SUM_FEE), SUM(SUM_RAKE) from GETTICKETTOURNAMENTS ' + WhereCond);
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    // ----
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 120;
    stg_GridReport.Columns[3].Width := 90;
    stg_GridReport.Columns[4].Width := 70;
    stg_GridReport.Columns[5].Width := 90;
    stg_GridReport.Columns[6].Width := 90;
    stg_GridReport.Columns[7].Width := 90;
    stg_GridReport.DataSource.DataSet.FieldByName('MONEY_PRIZE').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('BUY_IN').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('MONEY_PRIZE').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('SUM_RAKE').OnGetText := DBGridFormatNumber;
    stg_GridReport.DataSource.DataSet.FieldByName('SUM_FEE').OnGetText := DBGridFormatNumber;
  end
  else if lbl_ReportName.Hint = 'DATA_TRACKING' then
  begin
    pnl_ReportDetail.Visible := false;
    WhereCond := 'where trunc(DATETIME) between ' + '''' + DateToStr(dtp_ReportFrom.Date) + '''' + ' and ' + '''' + DateToStr(dtp_ReportTo.Date) + '''';
    Query := 'select DT.ID, DATETIME, NAME, SURNAME, USERNAME, COMPUTER_NAME, OPERATION, DB_TABLE, QUERY from DATA_TRACKING DT join USERS U ON U.ID=DT.USER_ID ' + WhereCond + OrderReportBy;
    QueryReport := Query;
    OracleDataSetReport.Close;
    OracleDataSetReport.SQL.Clear;
    OracleDataSetReport.SQL.Text := (Query);
    OracleDataSetReport.Open;
    stg_GridReport.Columns[0].Width := 0;
    stg_GridReport.Columns[1].Width := 120;
    stg_GridReport.Columns[2].Width := 110;
    stg_GridReport.Columns[3].Width := 70;
    stg_GridReport.Columns[4].Width := 70;
    stg_GridReport.Columns[5].Width := 120;
    stg_GridReport.Columns[6].Width := 70;
    stg_GridReport.Columns[7].Width := 70;
    stg_GridReport.Columns[8].Width := 300;
  end;
end;

procedure TFrmMain.btn_SaveClick(Sender: TObject);
var
  appINI: Tinifile;
begin
  appINI := Tinifile.Create(ChangeFileExt(Application.ExeName, '.ini'));
  try
    appINI.WriteString('Database', 'User', edt_DatabaseUser.Text);
    appINI.WriteString('Database', 'Pass', edt_DatabasePass.Text);
    appINI.WriteString('Database', 'TNS', edt_Database.Text);
    appINI.WriteString('WebCam', 'DeviceID', edt_WebCamDeviceId.Text);
    appINI.WriteBool('WebCam', 'InUse', chb_WebCamInUse.Checked);
  finally
    appINI.free;
  end;
end;

procedure TFrmMain.btn_UpdateAppInDBClick(Sender: TObject);
begin
  FrmLoading.Show;
  FrmLoading.ProgressBar1.Position := 30;
  FrmLoading.Repaint;
  UpdateAPPVersionInDB('LPM.EXE');
  FrmLoading.ProgressBar1.Position := 60;
  FrmLoading.Repaint;
  UpdateAPPVersionInDB('LPC.EXE');
  FrmLoading.ProgressBar1.Position := 90;
  FrmLoading.Repaint;
  UpdateAPPVersionInDB('LPT.EXE');
  FrmLoading.Close;
end;

procedure TFrmMain.Button10Click(Sender: TObject);
begin
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('update SETTINGS set GAME_DAY_START=' + 'to_date(''' + TimeToStr(dtp_GDTimeStart.Time) + ''', ''hh24:mi:ss'')');
  OracleQuery1.Execute;
  OracleSession1.Commit;
end;

procedure TFrmMain.Button1Click(Sender: TObject);
var
  ImageBlob: TLobLocator;
  PhotoFileName: string;
  PNG: TJPEGImage;
  APic: TPicture;
  i: Integer;
begin
  PhotoFileName := 'AAAAAAAA.JPG';
  for i := 0 to 500 do
  begin
    APic := GetImage('select IMAGE, IMAGE_TYPE from PLAYERS where id=' + inttostr(i), OracleSession1, false);
    if APic <> nil then
    begin
      ImageBlob := TLobLocator.CreateTemporary(OracleSession1, otBLOB, true);
      PNG := TJPEGImage.Create();
      PNG.Assign(APic);
      PNG := resizeImage(PNG, 106, 80);
      PNG.SaveToFile(PhotoFileName);
      // ----
      ImageBlob.LoadFromFile(PhotoFileName);
      OracleQuery1.SQL.Text := ('update PLAYERS set image_small=:IMAGE, image_type=' + '''' + 'JPG' + '''' + ' where id=' + inttostr(i));
      OracleQuery1.DeclareVariable(':IMAGE', otBLOB);
      OracleQuery1.SetComplexVariable(':IMAGE', ImageBlob);
      OracleQuery1.Execute;
      OracleSession1.Commit;
      OracleQuery1.Clear;
      FreeAndNil(ImageBlob);
      FreeAndNil(uUtils.resizeBmpImg);
      FreeAndNil(uUtils.resizeJpgImg);
      DeleteFile(PhotoFileName);
    end;
  end;
end;

procedure TFrmMain.Button6Click(Sender: TObject);
var
  appINI: Tinifile;
  ExeFile: string;
begin
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('update SETTINGS set CURRENCY_SYMBOL=' + '''' + edt_Currency_Symbol.Text + '''');
  OracleQuery1.Execute;
  OracleSession1.Commit;
  appINI := Tinifile.Create(ChangeFileExt(Application.ExeName, '.ini'));
  try
    appINI.WriteString('Database', 'User', edt_DatabaseUser.Text);
    appINI.WriteString('Database', 'Pass', edt_DatabasePass.Text);
    appINI.WriteString('Database', 'TNS', edt_Database.Text);
    appINI.WriteString('WebCam', 'DeviceID', edt_WebCamDeviceId.Text);
    appINI.WriteBool('WebCam', 'InUse', chb_WebCamInUse.Checked);
    appINI.WriteString('General', 'Language', com_Language.Text);
  finally
    appINI.free;
  end;
  ShowMessage(_('Press OK to restart Application.'));
  ExeFile := Application.ExeName;
  ShellExecute(0, 'open', Pchar(ExeFile), nil, nil, SW_SHOWNORMAL);
  Application.Terminate;
end;

procedure TFrmMain.Button9Click(Sender: TObject);
begin
  OracleQuery1.SQL.Clear;
  OracleQuery1.SQL.Text := ('update SETTINGS set DISPLAY_SEATING_TIME=' + '''' + edt_DisplaySeatingTime.Text + '''' + ',DISPLAY_REGISTERING_TIME=' + '''' + edt_DisplayRegisteringTime.Text + '''');
  OracleQuery1.Execute;
  OracleSession1.Commit;
end;

procedure TFrmMain.GetIniFile();
var
  appINI: Tinifile;
  iniFileName, Language: string;
begin
  iniFileName := ChangeFileExt(Application.ExeName, '.ini');
  if not FileExists(iniFileName) then
  begin
    FileCreate(iniFileName);
  end
  else
  begin
    appINI := Tinifile.Create(iniFileName);
    try
      edt_DatabaseUser.Text := appINI.ReadString('Database', 'User', '');
      edt_DatabasePass.Text := appINI.ReadString('Database', 'Pass', '');
      edt_Database.Text := appINI.ReadString('Database', 'TNS', '');
      edt_WebCamDeviceId.Text := appINI.ReadString('WebCam', 'DeviceId', '0');
      chb_WebCamInUse.Checked := appINI.ReadBool('WebCam', 'InUse', false);
      Language := appINI.ReadString('General', 'Language', '');
      ClientSocket1.Port := appINI.ReadInteger('RefreshService', 'Port', 0);
      ClientSocket1.Host := appINI.ReadString('RefreshService', 'Host', '');
      gnugettext.UseLanguage(Language);
      com_Language.Text := Language;
      OracleSession1.LogonUsername := edt_DatabaseUser.Text;
      OracleSession1.LogonPassword := edt_DatabasePass.Text;
      OracleSession1.LogonDatabase := edt_Database.Text;
    finally
      appINI.free;
    end;
  end;
end;

procedure TFrmMain.btn_CloseCageClick(Sender: TObject);
begin
  if pgc_Main.ActivePage <> tbs_Blank then
  begin
    FrmCageInventory.IsOpening := false;
    if FrmCageInventory.ShowModal = mrOK then
    begin
      pgc_Main.ActivePage := tbs_Blank;
    end;
  end;
end;

procedure TFrmMain.btn_CloseClick(Sender: TObject);
begin
  CloseApplication();
end;

procedure TFrmMain.ChangePassword1Click(Sender: TObject);
begin
  frmChangePassword.ShowChangePassForm(LoggedUserId);
end;

end.
